2012-06-14 100 views
3

問:現在我面臨着使用編程獲取android設備IP地址的問題。任何人都可以給出一個解決這個問題的代碼。我已經閱讀了很多關於它的線索,但沒有從中得到可靠的答案。請給我任何建議它的讚賞。 在此先感謝。如何在android中獲取主機IP地址?

+0

取決於你的意思是主機IP; 1.網絡接口的IP地址? 2.外部公共IP地址? – dacwe

+0

外部公共IP地址 –

+0

我想獲得公共IP地址 –

回答

5

的問題是,你可以不知道,如果你當前使用的網絡設備是真的有一個公共IP。但是,您可以檢查是否屬於這種情況,但您需要聯繫外部服務器。

在這種情況下,我們可以使用www.whatismyip.com檢查(almost copied from another SO question):

public static InetAddress getExternalIp() throws IOException { 
    URL url = new URL("http://automation.whatismyip.com/n09230945.asp"); 
    URLConnection connection = url.openConnection(); 
    connection.addRequestProperty("Protocol", "Http/1.1"); 
    connection.addRequestProperty("Connection", "keep-alive"); 
    connection.addRequestProperty("Keep-Alive", "1000"); 
    connection.addRequestProperty("User-Agent", "Web-Agent"); 

    Scanner s = new Scanner(connection.getInputStream()); 
    try { 
     return InetAddress.getByName(s.nextLine()); 
    } finally { 
     s.close(); 
    } 
} 

,以檢查該IP綁定到你的網絡接口之一:

public static boolean isIpBoundToNetworkInterface(InetAddress ip) { 

    try { 
     Enumeration<NetworkInterface> nets = 
      NetworkInterface.getNetworkInterfaces(); 

     while (nets.hasMoreElements()) { 
      NetworkInterface intf = nets.nextElement(); 
      Enumeration<InetAddress> ips = intf.getInetAddresses(); 
      while (ips.hasMoreElements()) 
       if (ip.equals(ips.nextElement())) 
        return true; 
     } 
    } catch (SocketException e) { 
     // ignore 
    } 
    return false; 
} 

測試代碼:

public static void main(String[] args) throws IOException { 

    InetAddress ip = getExternalIp(); 

    if (!isIpBoundToNetworkInterface(ip)) 
     throw new IOException("Could not find external ip"); 

    System.out.println(ip); 
} 
2

支持WiFi:

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

或更復雜的解決方案:

public String getLocalIpAddress() { 
    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()) { 
        return inetAddress.getHostAddress().toString(); 
       } 
      } 
     } 
    } catch (SocketException ex) { 
     Log.e(LOG_TAG, ex.toString()); 
    } 
    return null; 
}