使用Java获取当前机器的IP地址

我试图开发一个系统,在不同的系统上运行不同的节点,或者在同一个系统的不同端口上运行不同的节点。

现在所有节点都创build一个带有目标IP的Socket作为称为引导节点的特殊节点的IP。 节点然后创build自己的ServerSocket并开始监听连接。

引导节点维护一个节点列表,并在被查询时返回它们。

现在我需要的是节点必须注册自己的IP到引导节点。 我尝试使用cli.getInetAddress()一旦客户端连接到引导节点的ServerSocket ,但没有工作。

  1. 我需要客户端注册其PPP IP,如果可用的话;
  2. 否则LAN IP如果可用的话;
  3. 否则,假设它是同一台计算机,它必须注册127.0.0.1。

使用代码:

 System.out.println(Inet4Address.getLocalHost().getHostAddress()); 

要么

 System.out.println(InetAddress.getLocalHost().getHostAddress()); 

我的PPP连接IP地址是:117.204.44.192,但上面的返回给我192.168.1.2

编辑

我正在使用下面的代码:

 Enumeration e = NetworkInterface.getNetworkInterfaces(); while(e.hasMoreElements()) { NetworkInterface n = (NetworkInterface) e.nextElement(); Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); System.out.println(i.getHostAddress()); } } 

我能够获得所有与所有NetworkInterface相关的IP地址,但是我怎么区分它们? 这是我得到的输出:

 127.0.0.1 192.168.1.2 192.168.56.1 117.204.44.19 

在一般情况下,这可能有点棘手。

表面上, InetAddress.getLocalHost()应该给你这个主机的IP地址。 问题是主机可能有很多networking接口,并且一个接口可能绑定到多个IP地址。 最重要的是,并非所有的IP地址都可以在您的机器或您的局域网外访问。 例如,它们可以是虚拟networking设备的IP地址,专用networkingIP地址等等。

这意味着InetAddress.getLocalHost()返回的IP地址可能不是正确的。

你怎么处理这个?

  • 一种方法是使用NetworkInterface.getNetworkInterfaces()获取主机上所有已知的networking接口,然后迭代每个NI的地址。
  • 另一种方法是(以某种方式)获取主机的外部广告FQDN,并使用InetAddress.getByName()查找主IP地址。 (但是,如何获得它,以及如何处理基于DNS的负载平衡器?)
  • 之前的一个变体是从configuration文件或命令行参数中获得首选的FQDN。
  • 另一个变化是从configuration文件或命令行参数中获取首选的IP地址。

总之, InetAddress.getLocalHost()通常会起作用,但是您可能需要为在“复杂”networking环境中运行代码的情况提供另一种方法。


我能够获得与所有networking接口相关的所有IP地址,但我如何区分它们?

  • 127.xxx.xxx.xxx范围内的任何地址都是“回送”地址。 只有“这个”主机才能看到。
  • 192.168.xxx.xxx范围内的任何地址都是私有IP地址(又名本地IP地址)。 这些保留在组织内使用。 这同样适用于10.xxx.xxx.xxx地址和172.16.xxx.xxx到172.31.xxx.xxx。
  • 范围169.254.xxx.xxx中的地址是链接本地IP地址。 这些保留用于单个网段。
  • 224.xxx.xxx.xxx到239.xxx.xxx.xxx范围内的地址是组播地址。
  • 地址255.255.255.255是广播地址。
  • 其他任何东西都应该是一个有效的公共点对点IPv4地址。

事实上,InetAddress API提供了用于testing环回,本地链接,本地站点,多播和广播地址的方法。 你可以使用这些来找出你找回哪个IP地址是最合适的。

在这里发布https://issues.apache.org/jira/browse/JCS-40(Linux系统上的InetAddress.getLocalHost()不明确)的testingIP歧义解决方法代码:;

 /** * Returns an <code>InetAddress</code> object encapsulating what is most likely the machine's LAN IP address. * <p/> * This method is intended for use as a replacement of JDK method <code>InetAddress.getLocalHost</code>, because * that method is ambiguous on Linux systems. Linux systems enumerate the loopback network interface the same * way as regular LAN network interfaces, but the JDK <code>InetAddress.getLocalHost</code> method does not * specify the algorithm used to select the address returned under such circumstances, and will often return the * loopback address, which is not valid for network communication. Details * <a href="http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4665037">here</a>. * <p/> * This method will scan all IP addresses on all network interfaces on the host machine to determine the IP address * most likely to be the machine's LAN address. If the machine has multiple IP addresses, this method will prefer * a site-local IP address (eg 192.168.xx or 10.10.xx, usually IPv4) if the machine has one (and will return the * first site-local address if the machine has more than one), but if the machine does not hold a site-local * address, this method will return simply the first non-loopback address found (IPv4 or IPv6). * <p/> * If this method cannot find a non-loopback address using this selection algorithm, it will fall back to * calling and returning the result of JDK method <code>InetAddress.getLocalHost</code>. * <p/> * * @throws UnknownHostException If the LAN address of the machine cannot be found. */ private static InetAddress getLocalHostLANAddress() throws UnknownHostException { try { InetAddress candidateAddress = null; // Iterate all NICs (network interface cards)... for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements();) { NetworkInterface iface = (NetworkInterface) ifaces.nextElement(); // Iterate all IP addresses assigned to each card... for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements();) { InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); if (!inetAddr.isLoopbackAddress()) { if (inetAddr.isSiteLocalAddress()) { // Found non-loopback site-local address. Return it immediately... return inetAddr; } else if (candidateAddress == null) { // Found non-loopback address, but not necessarily site-local. // Store it as a candidate to be returned if site-local address is not subsequently found... candidateAddress = inetAddr; // Note that we don't repeatedly assign non-loopback non-site-local addresses as candidates, // only the first. For subsequent iterations, candidate will be non-null. } } } } if (candidateAddress != null) { // We did not find a site-local address, but we found some other non-loopback address. // Server might have a non-site-local address assigned to its NIC (or it might be running // IPv6 which deprecates the "site-local" concept). // Return this non-loopback candidate address... return candidateAddress; } // At this point, we did not find a non-loopback address. // Fall back to returning whatever InetAddress.getLocalHost() returns... InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); if (jdkSuppliedAddress == null) { throw new UnknownHostException("The JDK InetAddress.getLocalHost() method unexpectedly returned null."); } return jdkSuppliedAddress; } catch (Exception e) { UnknownHostException unknownHostException = new UnknownHostException("Failed to determine LAN address: " + e); unknownHostException.initCause(e); throw unknownHostException; } } 

你可以使用java的InetAddress类来达到这个目的。

 InetAddress IP=InetAddress.getLocalHost(); System.out.println("IP of my system is := "+IP.getHostAddress()); 

我的系统的输出=我的系统的IP of my system is := 10.100.98.228

getHostAddress()返回

以文本forms返回IP地址string。

或者你也可以做

 InetAddress IP=InetAddress.getLocalHost(); System.out.println(IP.toString()); 

输出= IP of my system is := RanRag-PC/10.100.98.228

 import java.net.DatagramSocket; try(final DatagramSocket socket = new DatagramSocket()){ socket.connect(InetAddress.getByName("8.8.8.8"), 10002); ip = socket.getLocalAddress().getHostAddress(); } 

当有多个networking接口时,这种方式很有效。 它始终返回首选的出站IP。 目的地8.8.8.8不需要可达。

在scala中的示例(在sbt文件中有用):

  import collection.JavaConverters._ import java.net._ def getIpAddress: String = { val enumeration = NetworkInterface.getNetworkInterfaces.asScala.toSeq val ipAddresses = enumeration.flatMap(p => p.getInetAddresses.asScala.toSeq ) val address = ipAddresses.find { address => val host = address.getHostAddress host.contains(".") && !address.isLoopbackAddress }.getOrElse(InetAddress.getLocalHost) address.getHostAddress } 

编辑1:更新的代码,因为上一个链接,不再存在

 import java.io.*; import java.net.*; public class GetMyIP { public static void main(String[] args) { URL url = null; BufferedReader in = null; String ipAddress = ""; try { url = new URL("http://bot.whatismyipaddress.com"); in = new BufferedReader(new InputStreamReader(url.openStream())); ipAddress = in.readLine().trim(); /* IF not connected to internet, then * the above code will return one empty * String, we can check it's length and * if length is not greater than zero, * then we can go for LAN IP or Local IP * or PRIVATE IP */ if (!(ipAddress.length() > 0)) { try { InetAddress ip = InetAddress.getLocalHost(); System.out.println((ip.getHostAddress()).trim()); ipAddress = (ip.getHostAddress()).trim(); } catch(Exception exp) { ipAddress = "ERROR"; } } } catch (Exception ex) { // This try will give the Private IP of the Host. try { InetAddress ip = InetAddress.getLocalHost(); System.out.println((ip.getHostAddress()).trim()); ipAddress = (ip.getHostAddress()).trim(); } catch(Exception exp) { ipAddress = "ERROR"; } //ex.printStackTrace(); } System.out.println("IP Address: " + ipAddress); } } 

实际版本:停止工作

希望这个片段可以帮助你实现这一点:

 // Method to get the IP Address of the Host. private String getIP() { // This try will give the Public IP Address of the Host. try { URL url = new URL("http://automation.whatismyip.com/n09230945.asp"); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String ipAddress = new String(); ipAddress = (in.readLine()).trim(); /* IF not connected to internet, then * the above code will return one empty * String, we can check it's length and * if length is not greater than zero, * then we can go for LAN IP or Local IP * or PRIVATE IP */ if (!(ipAddress.length() > 0)) { try { InetAddress ip = InetAddress.getLocalHost(); System.out.println((ip.getHostAddress()).trim()); return ((ip.getHostAddress()).trim()); } catch(Exception ex) { return "ERROR"; } } System.out.println("IP Address is : " + ipAddress); return (ipAddress); } catch(Exception e) { // This try will give the Private IP of the Host. try { InetAddress ip = InetAddress.getLocalHost(); System.out.println((ip.getHostAddress()).trim()); return ((ip.getHostAddress()).trim()); } catch(Exception ex) { return "ERROR"; } } } 

首先导入类

 import java.net.InetAddress; 

在class上

  InetAddress iAddress = InetAddress.getLocalHost(); String currentIp = iAddress.getHostAddress(); System.out.println("Current IP address : " +currentIp); //gives only host address 
 private static InetAddress getLocalAddress(){ try { Enumeration<NetworkInterface> b = NetworkInterface.getNetworkInterfaces(); while( b.hasMoreElements()){ for ( InterfaceAddress f : b.nextElement().getInterfaceAddresses()) if ( f.getAddress().isSiteLocalAddress()) return f.getAddress(); } } catch (SocketException e) { e.printStackTrace(); } return null; } 

使用InetAddress.getLocalHost()获取本地地址

 import java.net.InetAddress; try { InetAddress addr = InetAddress.getLocalHost(); System.out.println(addr.getHostAddress()); } catch (UnknownHostException e) { } 

您可以使用java.net.InetAddress API。 尝试这个 :

 InetAddress.getLocalHost().getHostAddress(); 

当你在寻找你的“本地”地址时,你应该注意到每台机器不仅有单一的networking接口,而且每个接口都有自己的本地地址。 这意味着你的机器总是拥有几个“本地”地址。

当连接到不同的端点时,不同的“本地”地址将被自动select使用。 例如,当您连接到google.com ,您正在使用“外部”本地地址; 但是当你连接到你的localhost ,你的本地地址总是localhost本身,因为本地主机只是一个回环。

以下是当您与google.com进行通信时如何查找您的本地地址:

 Socket socket = new Socket(); socket.connect(new InetSocketAddress("google.com", 80)); System.out.println(socket.getLocalAddress()); 

这是上面接受的答案的一个工作示例! 此NetIdentity类将存储内部主机IP以及本地回送。 如果您使用的是基于DNS的服务器,如上所述,则可能需要添加更多检查,或者可能需要执行“configuration文件路由”。

 import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Enumeration; /** * Class that allows a device to identify itself on the INTRANET. * * @author Decoded4620 2016 */ public class NetIdentity { private String loopbackHost = ""; private String host = ""; private String loopbackIp = ""; private String ip = ""; public NetIdentity(){ try{ Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while(interfaces.hasMoreElements()){ NetworkInterface i = interfaces.nextElement(); if(i != null){ Enumeration<InetAddress> addresses = i.getInetAddresses(); System.out.println(i.getDisplayName()); while(addresses.hasMoreElements()){ InetAddress address = addresses.nextElement(); String hostAddr = address.getHostAddress(); // local loopback if(hostAddr.indexOf("127.") == 0 ){ this.loopbackIp = address.getHostAddress(); this.loopbackHost = address.getHostName(); } // internal ip addresses (behind this router) if( hostAddr.indexOf("192.168") == 0 || hostAddr.indexOf("10.") == 0 || hostAddr.indexOf("172.16") == 0 ){ this.host = address.getHostName(); this.ip = address.getHostAddress(); } System.out.println("\t\t-" + address.getHostName() + ":" + address.getHostAddress() + " - "+ address.getAddress()); } } } } catch(SocketException e){ } try{ InetAddress loopbackIpAddress = InetAddress.getLocalHost(); this.loopbackIp = loopbackIpAddress.getHostName(); System.out.println("LOCALHOST: " + loopbackIp); } catch(UnknownHostException e){ System.err.println("ERR: " + e.toString()); } } public String getLoopbackHost(){ return loopbackHost; } public String getHost(){ return host; } public String getIp(){ return ip; } public String getLoopbackIp(){ return loopbackIp; } } 

当我运行这个代码时,我实际上得到了这样一个打印输出:

  Software Loopback Interface 1 -127.0.0.1:127.0.0.1 - [B@19e1023e -0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59 Broadcom 802.11ac Network Adapter -VIKING.yourisp.com:192.168.1.142 - [B@64b8f8f4 -fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2 Microsoft Kernel Debug Network Adapter Intel Edison USB RNDIS Device Driver for user-mode network applications Cisco Systems VPN Adapter for 64-bit Windows VirtualBox Host-Only Ethernet Adapter -VIKING:192.168.56.1 - [B@3cd1f1c8 -VIKING:fe80:0:0:0:d599:3cf0:5462:cb7%eth4 - [B@3a4afd8d LogMeIn Hamachi Virtual Ethernet Adapter -VIKING:25.113.118.39 - [B@1996cd68 -VIKING:2620:9b:0:0:0:0:1971:7627 - [B@3339ad8e -VIKING:fe80:0:0:0:51bf:994d:4656:8486%eth5 - [B@555590 Bluetooth Device (Personal Area Network) -fe80:0:0:0:4c56:8009:2bca:e16b%eth6:fe80:0:0:0:4c56:8009:2bca:e16b%eth6 - [B@3c679bde Bluetooth Device (RFCOMM Protocol TDI) Intel(R) Ethernet Connection (2) I218-V -fe80:0:0:0:4093:d169:536c:7c7c%eth7:fe80:0:0:0:4093:d169:536c:7c7c%eth7 - [B@16b4a017 Microsoft Wi-Fi Direct Virtual Adapter -fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1:fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1 - [B@8807e25 VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0000 VirtualBox Host-Only Ethernet Adapter-WFP Native MAC Layer LightWeight Filter-0000 VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0001 VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0002 VirtualBox Host-Only Ethernet Adapter-VirtualBox NDIS Light-Weight Filter-0000 VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0003 VirtualBox Host-Only Ethernet Adapter-QoS Packet Scheduler-0000 VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0004 VirtualBox Host-Only Ethernet Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000 VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0005 Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0000 Intel(R) Ethernet Connection (2) I218-V-WFP Native MAC Layer LightWeight Filter-0000 Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0001 Intel(R) Ethernet Connection (2) I218-V-Shrew Soft Lightweight Filter-0000 Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0002 Intel(R) Ethernet Connection (2) I218-V-VirtualBox NDIS Light-Weight Filter-0000 Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0003 Intel(R) Ethernet Connection (2) I218-V-QoS Packet Scheduler-0000 Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0004 Intel(R) Ethernet Connection (2) I218-V-WFP 802.3 MAC Layer LightWeight Filter-0000 Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0005 Broadcom 802.11ac Network Adapter-WFP Native MAC Layer LightWeight Filter-0000 Broadcom 802.11ac Network Adapter-Virtual WiFi Filter Driver-0000 Broadcom 802.11ac Network Adapter-Native WiFi Filter Driver-0000 Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0003 Broadcom 802.11ac Network Adapter-Shrew Soft Lightweight Filter-0000 Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0004 Broadcom 802.11ac Network Adapter-VirtualBox NDIS Light-Weight Filter-0000 Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0005 Broadcom 802.11ac Network Adapter-QoS Packet Scheduler-0000 Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0006 Broadcom 802.11ac Network Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000 Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0007 Microsoft Wi-Fi Direct Virtual Adapter-WFP Native MAC Layer LightWeight Filter-0000 Microsoft Wi-Fi Direct Virtual Adapter-Native WiFi Filter Driver-0000 Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0002 Microsoft Wi-Fi Direct Virtual Adapter-Shrew Soft Lightweight Filter-0000 Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0003 Microsoft Wi-Fi Direct Virtual Adapter-VirtualBox NDIS Light-Weight Filter-0000 Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0004 Microsoft Wi-Fi Direct Virtual Adapter-QoS Packet Scheduler-0000 Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0005 Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000 Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0006 

对于我的使用,我正在build立一个Upnp服务器,这有助于了解我所寻找的“模式”。 返回的一些对象是以太网适配器,networking适配器,虚拟networking适配器,驱动程序和VPN客户端适配器。 并非所有的东西都有地址。 所以你会想跳过没有的接口对象。

您也可以将其添加到当前NetworkInterface i的循环中

 while(interfaces.hasMoreElements()){ Enumeration<InetAddress> addresses = i.getInetAddresses(); System.out.println(i.getDisplayName()); System.out.println("\t- name:" + i.getName()); System.out.println("\t- idx:" + i.getIndex()); System.out.println("\t- max trans unit (MTU):" + i.getMTU()); System.out.println("\t- is loopback:" + i.isLoopback()); System.out.println("\t- is PPP:" + i.isPointToPoint()); System.out.println("\t- isUp:" + i.isUp()); System.out.println("\t- isVirtual:" + i.isVirtual()); System.out.println("\t- supportsMulticast:" + i.supportsMulticast()); } 

你会看到你的输出中的信息很像这样:

 Software Loopback Interface 1 - name:lo - idx:1 - max trans unit (MTU):-1 - is loopback:true - is PPP:false - isUp:true - isVirtual:false - supportsMulticast:true -ADRESS: [127.0.0.1(VIKING-192.168.56.1)]127.0.0.1:127.0.0.1 - [B@19e1023e -ADRESS: [0:0:0:0:0:0:0:1(VIKING-192.168.56.1)]0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59 Broadcom 802.11ac Network Adapter - name:wlan0 - idx:2 - max trans unit (MTU):1500 - is loopback:false - is PPP:false - isUp:true - isVirtual:false - supportsMulticast:true -ADRESS: [VIKING.monkeybrains.net(VIKING-192.168.56.1)]VIKING.monkeybrains.net:192.168.1.142 - [B@64b8f8f4 -ADRESS: [fe80:0:0:0:81fa:31d:21c9:85cd%wlan0(VIKING-192.168.56.1)]fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2 Microsoft Kernel Debug Network Adapter - name:eth0 - idx:3 - max trans unit (MTU):-1 - is loopback:false - is PPP:false - isUp:false - isVirtual:false - supportsMulticast:true 
 import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; public class IpAddress { NetworkInterface ifcfg; Enumeration<InetAddress> addresses; String address; public String getIpAddress(String host) { try { ifcfg = NetworkInterface.getByName(host); addresses = ifcfg.getInetAddresses(); while (addresses.hasMoreElements()) { address = addresses.nextElement().toString(); address = address.replace("/", ""); } } catch (Exception e) { e.printStackTrace(); } return ifcfg.toString(); } } 

一个相当简单的方法似乎正在工作…

 String getPublicIPv4() throws UnknownHostException, SocketException{ Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces(); String ipToReturn = null; while(e.hasMoreElements()) { NetworkInterface n = (NetworkInterface) e.nextElement(); Enumeration<InetAddress> ee = n.getInetAddresses(); while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); String currentAddress = i.getHostAddress(); logger.trace("IP address "+currentAddress+ " found"); if(!i.isSiteLocalAddress()&&!i.isLoopbackAddress() && validate(currentAddress)){ ipToReturn = currentAddress; }else{ System.out.println("Address not validated as public IPv4"); } } } return ipToReturn; } private static final Pattern IPv4RegexPattern = Pattern.compile( "^(([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); public static boolean validate(final String ip) { return IPv4RegexPattern.matcher(ip).matches(); } 

通常当我试图find我的公共IP地址,如cmyip.com或www.iplocation.net ,我使用这种方式:

 public static String myPublicIp() { /*nslookup myip.opendns.com resolver1.opendns.com*/ String ipAdressDns = ""; try { String command = "nslookup myip.opendns.com resolver1.opendns.com"; Process proc = Runtime.getRuntime().exec(command); BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream())); String s; while ((s = stdInput.readLine()) != null) { ipAdressDns += s + "\n"; } } catch (IOException e) { e.printStackTrace(); } return ipAdressDns ; } 

您可以尝试使用InetAddress类的isReachable()方法来确定哪个IP地址是您的真实公开可用IP地址。 我认为其他types的地址(站点本地,链接本地)不能从外面到达。

 while (ee.hasMoreElements()) { InetAddress i = (InetAddress) ee.nextElement(); System.out.println( i.getHostAddress() + i.isReachable(10*1000) ); } 
 public static String getIpAddress() { String ipAddress = null; try { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface networkInterface = networkInterfaces.nextElement(); byte[] hardwareAddress = networkInterface.getHardwareAddress(); if (null == hardwareAddress || 0 == hardwareAddress.length || (0 == hardwareAddress[0] && 0 == hardwareAddress[1] && 0 == hardwareAddress[2])) continue; Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses(); if (inetAddresses.hasMoreElements()) ipAddress = inetAddresses.nextElement().toString(); break; } } catch (SocketException e) { e.printStackTrace(); } return ipAddress; }