通常情况下安装VMware后,ipconfig会多出几个网卡
导致windows系统用InetAddress.getLocalHost().getHostAddress() 取不到本机的ip
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
/**
* @author yangguang
* @date 2018-10-27 14:57
* @description
*/
public class Test {
public static void main(String[] args) {
try {
StringBuilder sb = new StringBuilder();
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress() && inetAddress.isSiteLocalAddress()) {
//ipconfig下输出的ipaddress List
if(inetAddress.getHostAddress().contains("192.168.1.")) //选择本地网段192
sb.append(inetAddress.getHostAddress()+ "\n");
}
}
}
System.out.println(sb);
} catch (Exception e) {
e.printStackTrace();
}
}
}