第一种方法:
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()&&InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.v(TAG, ex.toString());
}
return null;
}
注:红色的是为是过滤掉ipv6即类似fe80::b607:f9ff:fee5:487e的IP地址,只返回ipv4的ip即172.20.4.1.1形式的ip
第二、wifi
private void getWifiAddr()
{
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
int wifiip=info.getIpAddress();
int sin=info.getRssi();
int strength = WifiManager.calculateSignalLevel(info.getRssi(),1);
.setText(longToIP(wifiip));
}
//将一个整形数转为172.20.4.231IP格式的字符串
public static String longToIP(long longIp) {
// linux long是低位在前,高位在后
StringBuffer sb = new StringBuffer("");
// 将高24位置0
sb.append(String.valueOf((longIp & 0xFF)));
sb.append(".");
// 将高16位置0,然后右移8位
sb.append(String.valueOf((longIp>> 8) & 0xFF));
sb.append(".");
// 将高8位置0,然后右移16位
sb.append(String.valueOf((longIp>> 16 & 0xFF)));
sb.append(".");
// 直接右移24位
sb.append(String.valueOf((longIp >> 24) & 0xFF));
return sb.toString();
}