Android读取IP地址?

时间:2013-05-31 08:06:16

标签: android networking ip-address android-wifi

我正在尝试读取isp不是本地的设备IP地址。

How to get IP address of the device from code?在这个经过检查的答案中,我给出了WI-FI的局域网IP地址,并提供了不同于互联网上的whatismyip的IP地址。我猜它可能是运营商服务提供商的本地IP。

我如何通过互联网IP地址来回复whatismyip?

public static String getPublicIP() throws IOException
{
    Document doc = Jsoup.connect("http://www.checkip.org").get();
    return doc.getElementById("yourip").select("h1").first().select("span").text();
}

这个可能有用,但我不想为它添加任何库。

smallBig编辑: http://api.exip.org/?call=ip 它只返回ip,我该如何使用它? 它可靠且寿命长吗?

2 个答案:

答案 0 :(得分:0)

如果您不想添加库,请使用URLConnection并自行解析。

答案 1 :(得分:-1)

public void getCurrentIP () {
  ip.setText("Please wait...");  
  try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet("http://whatismyip.everdot.org/ip");
        // HttpGet httpget = new HttpGet("http://whatismyip.com.au/");
        // HttpGet httpget = new HttpGet("http://www.whatismyip.org/");
        HttpResponse response;

        response = httpclient.execute(httpget);

        //Log.i("externalip",response.getStatusLine().toString());

        HttpEntity entity = response.getEntity();
        if (entity != null) {
                long len = entity.getContentLength();
                if (len != -1 && len < 1024) {
                        String str=EntityUtils.toString(entity);
                        //Log.i("externalip",str);
                        ip.setText(str);
                } else {
                        ip.setText("Response too long or error.");
                        //debug
                        //ip.setText("Response too long or error: "+EntityUtils.toString(entity));
                        //Log.i("externalip",EntityUtils.toString(entity));
                }            
        } else {
                ip.setText("Null:"+response.getStatusLine().toString());
        }

  }
  catch (Exception e)
  {
      ip.setText("Error");
  }

}
相关问题