2015-03-25 84 views
1

我需要知道,因爲當我發送廣播數據包時,我無法檢查它是否來自我自己。我的代碼問題是Android在桌面上工作正常。對於android它不斷給我一個IPV6,但它給我的廣播地址是正常的...如何從設備獲取默認IP地址?

回答

1

此功能將返回主機的IP地址。

private String getHostIpAddress() throws SocketException { 
    Enumeration<NetworkInterface> interfaces; 
    interfaces = NetworkInterface.getNetworkInterfaces(); 
    while (interfaces.hasMoreElements()) { 
     NetworkInterface current = interfaces.nextElement(); 
     if (!current.isUp() || current.isLoopback() || current.isVirtual()) 
      continue; 
     Enumeration<InetAddress> addresses = current.getInetAddresses(); 
     while (addresses.hasMoreElements()) { 
      InetAddress currentAddr = addresses.nextElement(); 
      if (currentAddr.isSiteLocalAddress()) 
       return currentAddr.getHostAddress();     
     } 
    } 
    return null; 
} 
0

您可以使用下面的代碼用於獲取設備的IP地址:

WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE); 
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());