在我的 android 设备中,我试图找到它的 IP 地址 (IPV4)。
如果我执行以下代码
InetAddress inet = InetAddress.getLocalHost();
System.out.println(inet.getHostAddress()); //giving me 127.0.0.1
代码给我 127.0.0.1。
我想获取实际IP 198.168.xx.xx。
(在我的电脑中,相同的代码为我提供了实际的 IP。)
最佳答案
public static String getIpAddress() {
try {
for (Enumeration en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()&&inetAddress instanceof Inet4Address) {
String ipAddress=inetAddress.getHostAddress().toString();
Log.e("IP address",""+ipAddress);
return ipAddress;
}
}
}
} catch (SocketException ex) {
Log.e("Socket exception in GetIP Address of Utilities", ex.toString());
}
return null;
}
授予权限
同时在 mainfest 中添加。
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
关于java - 获取我的局域网 IP 地址 (192.168.xxxx) (IPV4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17252018/