如何在java中询问我的外部IP地址

时间:2017-04-17 18:25:03

标签: java ip

我有一台路由器,当我用这个命令询问我的IP地址时: 。InetAddress.getLocalHost()getHostAddress(); 然后我得到了我的内在IP地址。 当我走进网站上的www.whatismyip.com页面时,我得到了另一个IP地址,那是我的真实地址。

我如何在Java中询问这个真实的IP地址?

...谢谢

2 个答案:

答案 0 :(得分:0)

    public class IP {

  public String myOuterIP() {
    return(readIP("http://checkip.amazonaws.com"));
  }

  public String readIP(String url) {
    String ip = "";
    try {
      URL whatIsMyIP = new URL(url);
      InputStreamReader ir =new InputStreamReader(whatIsMyIP.openStream());
      BufferedReader in = new BufferedReader(ir);
      ip = in.readLine();
    } catch (UnknownHostException e) {
      System.out.println("UnknownHostException");
    } catch (MalformedURLException e) {
      System.out.println("MalformedURLException");
    } catch (IOException e) {
      System.out.println("IOException");
    }
    return ip;
  }
}

这是我的结果和它的工作。网上有一个地址:http://checkip.amazonaws.com这是我的结果。

答案 1 :(得分:-1)

也许这样吗?

import org.apache.commons.io.IOUtils;
import java.io.BufferedInputStream;
import java.net.HttpURLConnection;
import java.net.URL;


URL url = new URL("http://myexternalip.com/raw");

HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

InputStream in = new BufferedInputStream(urlConnection.getInputStream());

String externalIP = IOUtils.toString(in, "UTF-8");