我正在使用ksoap2-android,我需要使用java获取IP地址,这样我就不必每次手动键入它。
IP地址是什么意思,例如,如果我使用命令 shell 执行ipconfig:
特定于连接的DNS后缀。 :
链接本地IPv6地址。 。 。 。 。 :f0::ed2:e3bf:8206:44%13
IPv4地址。 。 。 。 。 。 。 。 。 。 。 :192.168.1.107 子网掩码 。 。 。 。 。 。 。 。 。 。 。 :255.255.255.0
默认网关 。 。 。 。 。 。 。 。 。 :192.168.1.1
问题是正在开发一个android应用程序,并且仿真器具有与计算机的IP类型不同的IP。
我需要获取机器的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();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e(tag, ex.toString());
}
return "";
}