我正在尝试获取设备的 IP 地址,即使用 WIFI 或 3G 连接。我得到了无法理解的 IPV6 格式的 IP 地址。我想要 IPV4 格式的 IP 地址。我已经搜索过 google,但没有找到任何合适的解决方案。
这是我用来获取设备 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;
}
我得到了这个输出:
ip1--:/fe80::5054:ff:fe12:3456%eth0%2
ip2--:fe80::5054:ff:fe12:3456%eth0
应该是这样显示的:
192.168.1.1
请帮帮我..
最佳答案
尝试了很多技巧后..终于我可以得到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;
}
添加if条件如下图
/**This shows IPV4 format IP address*/
if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(ipv4 = inetAddress.getHostAddress())){}
而不是这个
/**This shows IPV6 format IP address*/
if (!inetAddress.isLoopbackAddress()){}
非常感谢.. 拉胡尔
检查地址是否为版本 4 地址的另一种方法是:
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address)
关于android - 如何获取 IPV4 格式的 IP 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11015912/