Android ServerSocket如何获取Server的lan ip地址

问题描述 投票:0回答:1

我使用这段代码是因为我很难获得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?
android serversocket
1个回答
0
投票

您可以使用以下代码段获取连接的路由器的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));
 }
© www.soinside.com 2019 - 2024. All rights reserved.