在使用java的Android项目中获取计算机的IP地址
我正在使用ksoap2-android,我需要使用java获取IP地址,这样我就不必每次都手动输入它。在使用java的Android项目中获取计算机的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,这是如何完成的?
非常感谢
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 "";
}
InetAddress iA=InetAddress.getLocalHost();
System.out.println(iA.getHostAddress());
请参见
嘿,这个客户端连接到@JigarJoshi的服务器的IP地址如何? – gumuruh 2014-09-11 09:07:51
为了让您的Android设备的Ipaddress:显示您使用此代码。
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = intToIp(ipAddress);
public String intToIp(int i) {
return ((i >> 24) & 0xFF) + "." +
((i >> 16) & 0xFF) + "." +
((i >> 8) & 0xFF) + "." +
(i & 0xFF) ;
}
如果他们没有启用WiFi,只需3G? – 2011-03-15 06:01:44
@Matt我不知道,但3G连接不提供IP地址? – asgs 2011-03-15 06:30:12
是的,他们这样做,我只是想知道这个代码是否仍然有效,就这些。 :) – 2011-03-15 15:21:26
这个工作适用于Android吗? – shadesco 2011-03-15 22:49:44
@ chadic是的,它的确如此。 – Hades 2011-03-16 07:01:08
尽管这确实起作用,但我得到了一些误报,我必须用正则表达式验证ip地址格式,这似乎适用于我的所有用例。 – broschb 2011-12-28 05:34:11