最近项目中需要获取手机端的IP地址,查了资料,发现网上的资料不全:
网上方法一:(在WiFi下获取)
public String GetHostWifiIp() {
//获取wifi服务
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
//判断wifi是否开启
if (!wifiManager.isWifiEnabled()) {
wifiManager.setWifiEnabled(true);
}
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = intToIp(ipAddress);
return ip;
}
private String intToIp(int i) {
return (i & 0xFF ) + "." +
((i >> 8 ) & 0xFF) + "." +
((i >> 16 ) & 0xFF) + "." +
( i >> 24 & 0xFF) ;
}
网上方法二:(据说可以通用,但是测试不行)
public static String GetHostGprsIp() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr
.hasMoreElements();) {
InetAddress inetAddress = ipAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {
Log.e("Error", ex.toString());
} catch (Exception e) {
Log.e("Error", e.toString());
}
return null;
}
,故我整理测试并测试得到:
public String GetIpAdd() {
// 判断wifi是否开启
String ipString = "";
//获取wifi服务
WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
if (wifiManager.isWifiEnabled()) {
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
// 格式转换
ipString = (ipAddress & 0xFF) + "." + ((ipAddress >> 8) & 0xFF)
+ "." + ((ipAddress >> 16) & 0xFF) + "."
+ ((ipAddress >> 24) & 0xFF);
} else { // 如果wifi没有开启的话,就获取3G的IP
try {
for (Enumeration<NetworkInterface> en = NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
// 遍历所有的网卡设备,一般移动设备上只有2张网卡,其中一张是环回网卡
for (Enumeration<InetAddress> enumIpAddr = intf
.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
// 过滤掉环回网卡和IPv6
if (!inetAddress.isLoopbackAddress()
&& !(inetAddress instanceof Inet6Address)) {
ipString = inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("TAG", "getIpAddr()" + ex.toString());
}
}
return ipString;
}
经测试,不管是WiFi下还是3g ,2g信号下都是可以的,希望可以帮助到别人!