由网友(潇湘夜雨笛悠悠)分享简介:在我的Android设备,我试图找到它的IP地址(IPv4)。如果我做了以下code InetAddress类INET = InetAddress.getLocalHost();的System.out.println(inet.getHostAddress()); //给我127.0.0.1在code是给我127...![新房装修 网络布局 WiFi快速变超人](https://p.xsw88.cn/allimgs/daicuo/20230906/904.png)
在我的Android设备,我试图找到它的IP地址(IPv4)。 如果我做了以下code
InetAddress类INET = InetAddress.getLocalHost();
的System.out.println(inet.getHostAddress()); //给我127.0.0.1
在code是给我127.0.0.1。 我想获得实际的IP 198.168.xx.xx。
(在我的电脑相同的code,虽然给我实际的IP地址。)
解决方案 公共静态字符串getIpAddress(){
尝试 {
对于(枚举EN = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements()){
NetworkInterface的INTF = en.nextElement();
为(枚举enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements()){
InetAddress类InetAddress类= enumIpAddr.nextElement();
如果(inetAddress.isLoopbackAddress()及!&安培; InetAddress类的instanceof Inet4Address){
字符串ip地址= inetAddress.getHostAddress()的toString()。
Log.e(IP地址,+ ip地址);
返回ip地址;
}
}
}
}赶上(SocketException前){
Log.e(套接字异常实用工具GetIP地址,ex.toString());
}
返回null;
}
![新房装修 网络布局 WiFi快速变超人](https://p.xsw88.cn/allimgs/daicuo/20230906/904.png)
授予权限
此外,在mainfest增加。
<使用-权限的Android:名称=android.permission.INTERNET对/>
<使用-权限的Android:名称=android.permission.ACCESS_NETWORK_STATE/>
In my android device I am trying to find its IP address(IPV4). If I do the following code
InetAddress inet = InetAddress.getLocalHost();
System.out.println(inet.getHostAddress()); //giving me 127.0.0.1
The code is giving me 127.0.0.1. I wanted to get the actual IP 198.168.xx.xx.
(In My pc the same code giving me the actual IP though.)
解决方案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;
}
Give permissions
Also add in mainfest.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
相关推荐
最新文章