Rah*_*dia 23 android ip-address android-networking android-4.0-ice-cream-sandwich
我试图获取设备的IP地址,即使用WIFI或3G连接.我收到了IPV6格式的IP地址,这是不可理解的.我想要IPV4格式的IP地址.我做了google但dint找到了任何合适的解决方案.
这是我用来获取设备IP地址的代码
public String getLocalIpAddress() {
try {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress = enumIpAddr.nextElement();
System.out.println("ip1--:" + inetAddress);
System.out.println("ip2--:" + inetAddress.getHostAddress());
if (!inetAddress.isLoopbackAddress()) {
String ip = inetAddress.getHostAddress().toString();
System.out.println("ip---::" + ip);
EditText tv = (EditText) findViewById(R.id.ipadd);
tv.setText(ip);
return inetAddress.getHostAddress().toString();
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我得到这个输出:
ip1--:/fe80::5054:ff:fe12:3456%eth0%2
ip2--:fe80::5054:ff:fe12:3456%eth0
Run Code Online (Sandbox Code Playgroud)
它应该显示如下:
192.168.1.1
Run Code Online (Sandbox Code Playgroud)
请帮帮我..
Rah*_*dia 47
尝试了很多技巧..最后我可以得到IPV4格式的IP地址..这是我的代码..
public String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
System.out.println("ip1--:" + inetAddress);
System.out.println("ip2--:" + inetAddress.getHostAddress());
// for getting IPV4 format
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())) {
String ip = inetAddress.getHostAddress().toString();
System.out.println("ip---::" + ip);
EditText tv = (EditText) findViewById(R.id.ipadd);
tv.setText(ip);
// return inetAddress.getHostAddress().toString();
return ip;
}
}
}
} catch (Exception ex) {
Log.e("IP Address", ex.toString());
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
如果条件如下所示添加
/**This shows IPV4 format IP address*/
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())){}
Run Code Online (Sandbox Code Playgroud)
而不是这个
/**This shows IPV6 format IP address*/
if (!inetAddress.isLoopbackAddress()){}
Run Code Online (Sandbox Code Playgroud)
非常感谢.. Rahul
检查地址是否为版本4地址的替代方法是:
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address)
Run Code Online (Sandbox Code Playgroud)
小智 8
您不能假设任何设备只有一个网络地址.您也不能假设它将具有任何IPv4 - 它可能只是IPv6,因此您的应用程序将需要能够处理IPv4和IPv6地址显示.
通常,Android手机至少有两个接口可以分配可用的IP地址,rmnet0用于3G数据,对于IPv4,它通常是运营商级NAT,因此不能接受传入的套接字连接,也可能有IPv6地址; 和wlan0用于wifi,它将具有可与其连接的网络协商的任何IPv4和/或IPv6地址.
某些版本的Android会故意丢弃(通常更昂贵的)rmnet0链接,当它连接到wifi时 - 试图减少3G数据的使用.当wifi附加到需要手动登录的强制门户网站时,此行为是一个问题.