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

Android关于获取到本机ip和mac地址

2016-10-15 14:45 281 查看
public static 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) {
ex.printStackTrace();
}
return null;
}
// 得到本机ip地址
public static String getLocalHostIp(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
Log.e(TAG, "getLocalHostIp: ip Int = " + dhcpInfo.ipAddress);
return FormatString(dhcpInfo.ipAddress);

}

//int高位放在数组低位,int低位放在数组高位
public static byte[] intToByteArray(int value) {
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
int offset = (b.length - 1 - i) * 8;
b[i] = (byte) ((value >>> offset) & 0xFF);
}
return b;
}

public static String FormatString(int value) {
String strValue = "";
byte[] ary = intToByteArray(value);
for (int i = ary.length - 1; i >= 0; i--) {
Log.e(TAG, "FormatString:  ary[" + i + "] = " + ary[i] + "  (ary[" + i + "] & 0xFF) = "
+ (ary[i] & 0xFF));
strValue += (ary[i] & 0xFF);
if (i > 0) {
strValue += ".";
}
}
return strValue;
}

// 得到本机Mac地址
public static String getLocalMac(Context context) {
WifiManager wifiMng = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfor = wifiMng.getConnectionInfo();
return wifiInfor.getMacAddress();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: