Java获取我的IP地址

我想用Java获取我的Internet IP地址,但是当我的IP地址是192.168.0.xxx时,我一直得到我的本地地址(即:127.0.0.1)

我正在使用这条线:

InetAddress.getLocalHost().getHostAddress(); 

这似乎是获取IP地址的标准,但它不是我想要的。 每个教程都说使用这一行,所以我有点困惑。

谁能告诉我如何才能得到正确的IP地址?


我正在运行连接到WiFi的设备,而我没有使用任何电缆。 我使用ifconfig inet addr给出的IP连接到服务器,我希望得到设备的inet addr。 我可以检查服务器端套接字的IP,但是如果设备(客户端)告诉服务器他希望其他设备连接哪个IP,那就更好了。

NetworkInterface类包含所有相关方法,但请注意,没有“我的IP”这样的东西。 一台机器可以有多个接口,每个接口可以有多个IP。

您可以使用此类列出它们,但是从列表中选择的接口和IP取决于您使用此IP所需的内容。

InetAddress.getLocalHost()不咨询您的接口,它只返回常量127.0.0.1(对于IPv4))

  String ip; try { Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface iface = interfaces.nextElement(); // filters out 127.0.0.1 and inactive interfaces if (iface.isLoopback() || !iface.isUp()) continue; Enumeration addresses = iface.getInetAddresses(); while(addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); ip = addr.getHostAddress(); System.out.println(iface.getDisplayName() + " " + ip); } } } catch (SocketException e) { throw new RuntimeException(e); } 

我们问问AWS

 URL url = new URL("http://checkip.amazonaws.com/"); BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream())); System.out.println(br.readLine()); 

编辑

在你投票之前,我很清楚这不是一个java解决方案。 它是任何编程语言的通用解决方案。 其他解决方案对我来说效果不佳。 另外我相信知道你的IP的更简单方法是上网。 它可以是任何站点,服务器可以返回它在请求中获得的客户端ip。 您可以为它设置自己的端点。

默认网络接口的另一种选择,只是我在5分钟前尝试并看到你的问题:)

 InetAddress[] localaddr; try { localaddr = InetAddress.getAllByName("host.name"); for(int i = 0; i < localaddr.length; i++){ System.out.println("\n" + localaddr[i].getHostAddress()); } } catch (UnknownHostException e) { e.printStackTrace(); } 

有同样的问题,在这个页面上找到了解决方案: http : //mrhawy.blogspot.it/2012/05/how-to-get-your-external-ip-address-in.html

  public String getIpAddress() throws MalformedURLException, IOException { URL myIP = new URL("http://api.externalip.net/ip/"); BufferedReader in = new BufferedReader( new InputStreamReader(myIP.openStream()) ); return in.readLine(); } 

从长远来看,这段代码遇到了一些麻烦,一周内几次服务器都不会回复。

新解决方案:

 public static String getIpAddress() { URL myIP; try { myIP = new URL("http://api.externalip.net/ip/"); BufferedReader in = new BufferedReader( new InputStreamReader(myIP.openStream()) ); return in.readLine(); } catch (Exception e) { try { myIP = new URL("http://myip.dnsomatic.com/"); BufferedReader in = new BufferedReader( new InputStreamReader(myIP.openStream()) ); return in.readLine(); } catch (Exception e1) { try { myIP = new URL("http://icanhazip.com/"); BufferedReader in = new BufferedReader( new InputStreamReader(myIP.openStream()) ); return in.readLine(); } catch (Exception e2) { e2.printStackTrace(); } } } return null; } 
 //This program is find your exact LAN(Local Machine on which your are //runing this program) IP Address import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; public class GetMyIPAddress { public static void main(String gks[]) throws SocketException{ Enumeration e = NetworkInterface.getNetworkInterfaces(); int ctr=0; while(e.hasMoreElements()) { NetworkInterface n = (NetworkInterface) e.nextElement(); Enumeration ee = n.getInetAddresses(); while (ee.hasMoreElements() && ctr<3) { ctr++; if(ctr==3) break; InetAddress i = (InetAddress) ee.nextElement(); if(ctr==2) System.out.println(i.getHostAddress()); } } } } 

我的解决方案只返回1个Ip4地址:

 try { Enumeration interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface iface = interfaces.nextElement(); if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint()) continue; Enumeration addresses = iface.getInetAddresses(); while(addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); final String ip = addr.getHostAddress(); if(Inet4Address.class == addr.getClass()) return ip; } } } catch (SocketException e) { throw new RuntimeException(e); } return null; 

这是我获取IP地址的方法。

  1. 获取您的默认网关地址
  2. 获取PC中的所有地址
  3. 现在在您的IP(假设为192.168.100.4)和默认网关IP(假设为192.168.100.1)中,前9位地址必须相同,因此满足此条件的IP就是您的IP。

请参阅下面的完整工作代码。

 import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import java.util.Iterator; import java.util.StringTokenizer; import java.util.TreeSet; public class MyIpAddress { public static void main(String[] args) { // doPortForwarding(); MyIpAddress myIpAddress = new MyIpAddress(); // get default address String yourIp = myIpAddress.getYourIp(myIpAddress .getDefaultGateWayAddress()); System.out.println(yourIp); // get } // amin // return ip address for which u need to do port forwarding private String getYourIp(String defaultAddress) { String temp = defaultAddress.substring(0, 11); String ipToForward = ""; TreeSet ipAddrs = getIpAddressList(); for (Iterator iterator = ipAddrs.iterator(); iterator.hasNext();) { String tempIp = iterator.next(); if (tempIp.contains(temp)) { ipToForward = tempIp; break; } } return ipToForward; }// ipForPortForwarding // get the ipaddress list private TreeSet getIpAddressList() { TreeSet ipAddrs = new TreeSet(); try { Enumeration interfaces = NetworkInterface .getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface iface = interfaces.nextElement(); // filters out 127.0.0.1 and inactive interfaces if (iface.isLoopback() || !iface.isUp()) continue; Enumeration addresses = iface.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress addr = addresses.nextElement(); ipAddrs.add(addr.getHostAddress()); }// 2 nd while }// 1 st while } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ipAddrs; }// getIpAddressList // get default gateway address in java private String getDefaultGateWayAddress() { String defaultAddress = ""; try { Process result = Runtime.getRuntime().exec("netstat -rn"); BufferedReader output = new BufferedReader(new InputStreamReader( result.getInputStream())); String line = output.readLine(); while (line != null) { if (line.contains("0.0.0.0")) { StringTokenizer stringTokenizer = new StringTokenizer(line); stringTokenizer.nextElement();// first string is 0.0.0.0 stringTokenizer.nextElement();// second string is 0.0.0.0 defaultAddress = (String) stringTokenizer.nextElement(); // this is our default address break; } line = output.readLine(); }// while } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return defaultAddress; }// getDefaultAddress } 

你需要获取jsoup jar在你的java项目中添加jar的jsoup并解释这行代码,你将得到你的ip地址,

 Document doc = Jsoup.connect("https://whatismyipaddress.com/").timeout(10000).get() ; Elements el = doc.select("div#section_left") ; Element e = el.select("a").get( System.out.println(e.text());