我在stackoverflow中看到了关于这个问题的一些答案。我的代码的主要区别在于它只获取公共IP地址,通过在发现环回接口或用于点对点连接的IP时继续。
Obs:我正在与localhost的IP进行比较,因为我是VirtualBox,localhost是用来与该机器通信的IP。我想知道为什么。该方法返回一个String,但它很容易就是InetAddress。反馈总是很好。谢谢:))
答案 0 :(得分:2)
private String getPublicIpAddress() {
String res = null;
try {
String localhost = InetAddress.getLocalHost().getHostAddress();
Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
while (e.hasMoreElements()) {
NetworkInterface ni = (NetworkInterface) e.nextElement();
if(ni.isLoopback())
continue;
if(ni.isPointToPoint())
continue;
Enumeration<InetAddress> addresses = ni.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress address = (InetAddress) addresses.nextElement();
if(address instanceof Inet4Address) {
String ip = address.getHostAddress();
if(!ip.equals(localhost))
System.out.println((res = ip));
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}