public static List<String> getLocalIP() {
List<String> localIps=new ArrayList<String>();
InetAddress ip = null;
try {
// 如果是Windows操作系统
if (false) {//经过测试一样可以使用isWindowsOS();所以禁用window方式
ip = InetAddress.getLocalHost();
}
// 如果是Linux操作系统
else {
Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
.getNetworkInterfaces();
while (netInterfaces.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
// ----------特定情况,可以考虑用ni.getName判断
// 遍历所有ip
Enumeration<InetAddress> ips = ni.getInetAddresses();
while (ips.hasMoreElements()) {
ip = (InetAddress) ips.nextElement();
//System.out.println(ip.getHostAddress()+"-----"+ip.isSiteLocalAddress()+"-----"+ip.isLoopbackAddress()+"----"+ip.getHostName());
if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 127.开头的都是lookback地址
localIps.add(ip.getHostAddress());
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return localIps;
}
获取本机ip地址,并自动区分Windows还是linux操作系统
最新推荐文章于 2022-10-20 20:25:35 发布