Android ServerSocket 如何获取服务器的局域网 IP 地址



我使用了这段代码,因为我正在努力获取ServerSocket的Lan(Wifi(IP地址。

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

ipAddress 的值为:

fe80::6a96:65a4:2cd8:bf8a%wlan0

如何从中获取可读的 IP 地址? 例如

192.18.1.10 Etc?

您可以使用以下代码片段获取连接的路由器的 IP 地址。它会给你格式类似于 192.168.0.10。

 WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
 if (wifiManager.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
         DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
         int serverAddress = dhcpInfo.serverAddress;
         String routersIPAddress=String.format(Locale.US, "%d.%d.%d.%d", (serverAddress & 0xff), (serverAddress >> 8 & 0xff), (serverAddress >> 16 & 0xff), (serverAddress >> 24 & 0xff));
 }

最新更新