我试图获取设备的IP地址,即使用WIFI或3G连接。我获得的是IPV6格式的IP地址,但这种格式不易理解。我想要获得IPV4格式的IP地址,我已经尝试过谷歌搜索,但未找到合适的解决方案。
以下是我使用的代码来获取设备的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
请帮助我解决这个问题...