我想在连接到 wifi 网络时获取运行我的应用程序的用户手机上的本地 IPv4 地址。使用以下代码:
WifiManager wm = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
hostname = ip;
我可以获得接近 IPv4 地址的信息,但与命令行中的 IPv4 地址相比,它并不完全相同。有更好的方法来解决这个问题吗?我知道 formatIpAddress 已被弃用,但在我找到获取 IPv4 地址的方法之前,我现在并不太担心这一点。
编辑:
我发现手机 wifi 设置中的 IP 地址是我使用建议的解决方案获取 IP 地址的解决方案时得到的。有没有办法在ip config客户端获取ip地址?
最佳答案
代码打印运行 Android 或 java 应用程序的设备的本地 IPv4 地址。
try {
Enumeration networkInterfaces = NetworkInterface.getNetworkInterfaces(); // gets All networkInterfaces of your device
while (networkInterfaces.hasMoreElements()) {
NetworkInterface inet = (NetworkInterface) networkInterfaces.nextElement();
Enumeration address = inet.getInetAddresses();
while (address.hasMoreElements()) {
InetAddress inetAddress = (InetAddress) address.nextElement();
if (inetAddress.isSiteLocalAddress()) {
System.out.println("Your ip: " + inetAddress.getHostAddress()); /// gives ip address of your device
}
}
}
} catch (Exception e) {
// Handle Exception
}
关于java - 使用java获取本地网络的IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45742193/