2013-05-31 82 views
0

我正在嘗試讀取從isp本地提供的設備IP地址。Android讀取IP地址?

How to get IP address of the device from code?在這個檢查的答案給我LAN Ip地址WI-FI,並給出不同的IP地址比單元格互聯網上的whatismyip。我想這可能是運營商服務提供商的本地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,我該如何使用它? 它是可靠和長壽?

+0

如果您身在代理之後,服務可能會在您使用單元時爲您提供該IP。取決於你將要使用它的實際IP whatismyip返回的是_NOT_你在找什麼。 – Nanne

+0

@Nanne, 我不使用任何代理,我希望它用於ftp和遠程控制。我想,什麼返回wahtismyip是我所尋找的ISP或單元WAN IP。 –

+1

但它可能是你的ISP使用某種代理。如果您的銷售具有不同的IP,那麼無論什麼whatismyip返回,那麼您將無法連接 - >如果您連接到'whatismyip'地址,它不會知道將請求發送到您的手機,就像使用本地LAN IP和你的廣域網ip在家裏(wifi)。所以你需要的是你的設備的本地IP。如果那與'whatismyip'的地址不同,你就背後是某種更復雜的東西(NAT?),你將不會得到太多的幫助通過檢索其他地址 – Nanne

回答

0

如果您不想添加庫,請使用URLConnection並自己進行解析。

+0

我該如何閱讀? –

+0

我如何閱讀並返回這個http://api.exip.org/?call=ip –

-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"); 
    } 

} 
+0

它返回一個錯誤爲'android.os.NetworkOnMainThreadException' :( –

+1

從JellyBean開始,任何網絡訪問代碼必須是運行在一個單獨的線程中,即除主/ UI線程以外 – midhunhk

+1

@IAMTHEANSWER在我的一個應用程序中有代碼,不知道它來自哪裏,對不起:) –