2011-05-20 108 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