2011-05-20 66 views
1

我正在开发android 2.1中的应用程序,我想显示外部IP。我怎么能这样做?提前致谢。Android获取外部IP

+0

你认为什么是“外部”IP地址? – Squonk 2011-05-20 21:09:31

回答

14
public void getCurrentIP() { 
    ip.setText("Please wait..."); 
    try { 
      HttpClient httpclient = new DefaultHttpClient(); 
      HttpGet httpget = new HttpGet("http://ifcfg.me/ip"); 
      // HttpGet httpget = new HttpGet("http://ipecho.net/plain"); 
      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"); 
    } 

} 
+1

http://whatismyip.akamai.com/ 不错:但是使用AsyncTask的这个URL。 – 2014-06-18 14:42:55

+0

@TusharPandey为什么whatismyip.akamai.com最新问题与http://ifcfg.me/ip – wadali 2017-11-24 08:31:44

+1

如果你想要json数据https://ifcfg.me/json – wadali 2017-11-24 08:34:00

1

我不认为有办法以编程方式执行它,但你可以调用一个像http://www.whatismyip.com/这样的站点,然后从页面中去除IP。您可能希望找到提供API并支持第三方调用的网站。

-2

看看这个代码片段:

String ipAddress = null; 
    try { 
     for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { 
      NetworkInterface intf = en.nextElement(); 
      for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 
       InetAddress inetAddress = enumIpAddr.nextElement(); 
       if (!inetAddress.isLoopbackAddress()) { 
        ipAddress = inetAddress.getHostAddress().toString(); 
       } 
      } 
     } 
    } catch (SocketException ex) { 
     ex.printStackTrace(); 
    } 

    Log.e("IP ADDRESS:", ipAddress); 
+0

获取本地IP而非外部IP – inVINCEable 2014-12-22 18:32:37