您的位置:首页 > 移动开发 > Android开发

android 获取设备信息的IP地址和Mac地址—亲测无误!!

2018-01-03 16:44 751 查看

前言

方便的获取IP,Mac地址信息的工具类,记录一下,方便以后查阅。亲测无误。

获取IP地址

public static String getIpAddress(Context context){
NetworkInfo info = ((ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info != null && info.isConnected()) {
// 3/4g网络
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {
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() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}

} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {
//  wifi网络
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ipAddress = intIP2StringIP(wifiInfo.getIpAddress());
return ipAddress;
}  else if (info.getType() == ConnectivityManager.TYPE_ETHERNET){
// 有限网络
return getLocalIp();
}
}
return null;
}

private static String intIP2StringIP(int ip) {
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
(ip >> 24 & 0xFF);
}

// 获取有限网IP
private static String getLocalIp() {
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()
&& inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException ex) {

}
return "0.0.0.0";

}


注意:IP地址不是唯一的,不同的网络下IP地址是变化的,在移动数据网络,不同的无线网,有线网下IP地址是不一样的。

获取Mac地址

public static String getMacAddressFromIp(Context context) {
String mac_s= "";
StringBuilder buf = new StringBuilder();
try {
byte[] mac;
NetworkInterface ne=NetworkInterface.getByInetAddress(InetAddress.getByName(getIpAddress(context)));
mac = ne.getHardwareAddress();
for (byte b : mac) {
buf.append(String.format("%02X:", b));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
mac_s = buf.toString();
} catch (Exception e) {
e.printStackTrace();
}

return mac_s;
}


这是通过IP地址来获取Mac地址。获取IP地址的方法在上面。

Mac地址是取决于网卡,因为设备有有线网卡和无线网卡,所以在有线网络和无线网络下的Mac地址是不同的。不同的无线网络下Mac地址是一样的,因为无线网卡是同一个。

当然如果设备只有一种网卡的话,那Mac地址就是唯一的了。Mac地址可通过xposed等一些黑科技来修改。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android mac IP-address