代码如下:
public static String getCurrentHostIpAddress() {
Enumeration<NetworkInterface> n;
try {
n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements(); ) {
NetworkInterface e = n.nextElement();
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements(); ) {
InetAddress addr = a.nextElement();
String ipAddress = addr.getHostAddress();
if (!ipAddress.equals("127.0.0.1")
&& ipAddress.indexOf(":") == -1) {
return ipAddress;
}
}
}
throw new RuntimeException(
"Can't get the current host ip address.");
} catch (SocketException e1) {
throw new RuntimeException(
"Can't get the current host ip address:" + e1);
}
}


发布评论