如何在java中仅获取公共IP地址
我在stackoverflow中看到了关于这个问题的一些答案。我的代码的主要区别在于,它只获取公共IP地址,方法是在找到环回接口或点对点连接的IP时继续 Obs:我将其与本地主机的IP进行比较,因为在VirtualBox中,本地主机是用于与该机器通信的IP。我想知道为什么。该方法返回一个字符串,但很可能是InetAddress。反馈总是很好的。谢谢:)如何在java中仅获取公共IP地址,java,Java,我在stackoverflow中看到了关于这个问题的一些答案。我的代码的主要区别在于,它只获取公共IP地址,方法是在找到环回接口或点对点连接的IP时继续 Obs:我将其与本地主机的IP进行比较,因为在VirtualBox中,本地主机是用于与该机器通信的IP。我想知道为什么。该方法返回一个字符串,但很可能是InetAddress。反馈总是很好的。谢谢:)私有字符串getPublicIpAddress(){ 字符串res=null; 试一试{ 字符串localhost=InetAddress.get
私有字符串getPublicIpAddress(){
字符串res=null;
试一试{
字符串localhost=InetAddress.getLocalHost().getHostAddress();
枚举e=NetworkInterface.getNetworkInterfaces();
而(e.hasMoreElements()){
NetworkInterface ni=(NetworkInterface)e.nextElement();
if(ni.isLoopback())
继续;
if(ni.isPointToPoint())
继续;
枚举地址=ni.getInetAddresses();
while(addresses.hasMoreElements()){
InetAddress地址=(InetAddress)地址。nextElement();
if(Inet4Address的地址实例){
字符串ip=address.getHostAddress();
如果(!ip.equals(localhost))
System.out.println((res=ip));
}
}
}
}捕获(例外e){
e、 printStackTrace();
}
返回res;
}
您还应该测试Inet4Addr对象,看看它们是否是“站点本地”、“链接本地”和其他一些东西。好啊我没有考虑这些方法,但这可能是进行所有比较的最佳方法。谢谢斯蒂芬!
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;
}