Java getting my IP address

前端 未结 10 2395
没有蜡笔的小新
没有蜡笔的小新 2020-11-27 16:53

I am trying to get my Internet IP address in Java but I keep getting my local address (ie: 127.0.0.1), when my IP address is 192.168.0.xxx

I am using the line:

10条回答
  •  一向
    一向 (楼主)
    2020-11-27 17:33

    Had the same problem, found the solution on this page: 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();
      }
    

    had some troubles with this code on the long run, several times in a week the server just won't reply.

    new solution:

    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;
    }
    

提交回复
热议问题