1. 遍历网络
接口来获取IP地址:
class="java">
Enumeration<?> e1;
String currentIP = "";
e1 = (Enumeration<?>) NetworkInterface.getNetworkInterfaces();
outer: while (e1.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e1.nextElement();
String displayName = ni.getDisplayName();
String name = ni.getName();
if (name.indexOf("eth") < 0 && displayName.indexOf("Wireless") < 0) { // 只获取网卡或者无线网卡的IP,根据需要配置。
continue;
}
Enumeration<?> e2 = ni.getInetAddresses();
while (e2.hasMoreElements()) {
InetAddress ia = (InetAddress) e2.nextElement();
if (ia instanceof Inet6Address) {
continue;
}
currentIP = ia.getHostAddress();
System.out.println(name + ">" + currentIP);
break outer;
}
}
2. 通过InetAddress来获取IP地址:
InetAddress address = InetAddress.getLocalHost();
String hostAddress = address.getHostAddress();
System.out.println(hostAddress);
如果本机装了网卡,无线网卡以及虚拟机,通过上面这种方式获取的可能不是需要的IP地址。