之所以使用这段代码,是因为我在努力获取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?
答案 0 :(得分: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));
}