2014-10-27 81 views
0

我嘗試使用以下代碼獲取互聯網動態IP地址,當提供移動連接時。 getHostAddress返回10.13.x.x ssid內部主機地址。但我想獲得作爲178.240.x.x動態互聯網IP地址。感謝您的建議。獲取IP地址(互聯網動態IP)

for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { 
        InetAddress inetAddress = enumIpAddr.nextElement(); 
        if (!inetAddress.isLoopbackAddress()) { 
         networkIpAdress = inetAddress.getHostAddress().toString(); 
        } 
       } 
+2

您需要爲此提供外部資源,如此處所述:http://stackoverflow.com/a/16781615/2413303 – EpicPandaForce 2014-10-27 09:27:07

回答

0

如果您的設備與無線網絡連接,然後

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE); 
WifiInfo wifiInfo = wifiManager.getConnectionInfo(); 
int ipAddress = wifiInfo.getIpAddress(); 

的Android設備都可以通過WiFi進行連接,3G等,這顯然有不同的IP地址。 每次重新連接時,3G上的IP地址也會發生變化。

0

我用下面的代碼解決了我的問題。

HttpClient httpclient = new DefaultHttpClient(); 
    HttpGet httpget = new HttpGet("http://ip2country.sourceforge.net/ip2c.php?format=JSON"); 
    HttpResponse response; 
    response = httpclient.execute(httpget); 
    HttpEntity entity = response.getEntity(); 
    entity.getContentLength(); 
    JSONObject json_data = new JSONObject(EntityUtils.toString(entity)); 
    String networkIpAdress = json_data.getString("ip");