【问题标题】:Java getting my IP addressJava 获取我的 IP 地址
【发布时间】:2011-12-26 09:02:31
【问题描述】:

我正在尝试在 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 会更好。

【问题讨论】:

  • 您是否可以通过 localhost 连接到服务器?这段代码是在服务器上运行的,还是在桌面应用程序上运行的,还是什么?
  • 什么是“IP地址”?我的电脑目前至少有五个。
  • 来自文档的嗯:If there is a security manager, its checkConnect method is called with the local host name and -1 as its arguments to see if the operation is allowed. If the operation is not allowed, an InetAddress representing the loopback address is returned.
  • 我在连接到 WiFi 的设备上运行,但我没有使用任何电缆。我正在使用 ifconfig inet addr 提供的 IP 连接到服务器,并且我正在寻找设备的 inet addr。
  • 我可以检查服务器端套接字的 IP,但我认为如果设备(客户端)告诉服务器他希望其他设备连接到哪个 IP 会更好。

标签: java ip wifi


【解决方案1】:
    String ip;
    try {
        Enumeration<NetworkInterface> 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<InetAddress> 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);
    }

【讨论】:

    【解决方案2】:

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

    您可以使用此类将它们全部列出,但您从列表中选择的接口和 IP 取决于您使用此 IP 的确切需要。

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

    【讨论】:

      【解决方案3】:

      让我们问问 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。您可以为其设置自己的端点。

      【讨论】:

      • 这将获取 WAN IP 地址,并且在大多数情况下与 LAN IP 地址不同,这就是问题所在。
      【解决方案4】:

      遇到了同样的问题,在这个页面找到了解决方案: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;
      }
      

      【讨论】:

        【解决方案5】:

        默认网络接口的另一个选项,就在我 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();
        }
        

        【讨论】:

          【解决方案6】:
          //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());
          
                  }
              }
          }
          
          }
          

          【讨论】:

            【解决方案7】:

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

            try {
                Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
                while (interfaces.hasMoreElements()) {
                    NetworkInterface iface = interfaces.nextElement();
                    if (iface.isLoopback() || !iface.isUp() || iface.isVirtual() || iface.isPointToPoint())
                        continue;
            
                    Enumeration<InetAddress> 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;
            

            【讨论】:

              【解决方案8】:

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

              1. 获取您的默认网关地址
              2. 获取您电脑中的所有地址
              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<String> ipAddrs = getIpAddressList();
                      for (Iterator<String> 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<String> getIpAddressList() {
                      TreeSet<String> ipAddrs = new TreeSet<String>();
              
                      try {
                          Enumeration<NetworkInterface> 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<InetAddress> 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
              }
              

              【讨论】:

                【解决方案9】:

                你需要得到jsoup的jar here 在你的java项目中添加jsoup的jar并解释这行代码,你就会得到你的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());
                

                【讨论】:

                  【解决方案10】:

                  您可以通过编写简单的代码来获取您的 IP 地址。 `

                  import java.net.InetAddress;
                  
                  public class Main {
                      public static void main(String[] args) throws Exception
                      {
                          System.out.println(InetAddress.getLocalHost());
                      }
                  }
                  

                  【讨论】:

                    猜你喜欢
                    • 2010-10-29
                    • 2010-09-15
                    • 2013-12-04
                    • 1970-01-01
                    • 2010-12-13
                    • 2013-05-19
                    • 2012-04-12
                    • 2013-08-19
                    • 2010-11-04
                    相关资源
                    最近更新 更多