android - 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));
}
推荐阅读
- java - JavaFX UI 在事件侦听器中的 JavaFX 应用程序线程中冻结,但可与 Platform.runLater 一起使用
- neo4j - 将 Neo4j 添加到 Gremlin 服务器 - 如何?
- git - 如何重新定位整个提交图?
- reactjs - 将 Prop 传递给函数
- selenium - Selenium + sikuli 错误 - *No ClassDefFoundError: org/sikuli/script/Screen* 在命令提示符中
- python - 使用 Tensorflow 进行训练时如何正确实施验证?
- python - python在导入期间停止
- mongodb - MongoDB插入文档时出错,我该如何解决?
- python - 使用 Python 的 Elasticsearch JSON 批量索引
- react-native - React - 如何测试装饰类