
第一種方法:
(1)設(shè)備開通Wifi連接,獲取到網(wǎng)卡的MAC地址和IP地址(但是不開通wifi,這種方法獲取不到Mac地址,這種方法也是網(wǎng)絡(luò)上使用的最多的方法)
//根據(jù)Wifi信息獲取本地Mac
public static voidgetLocalMacAddressFromWifiInfo(Context context)
{
WifiManagerwifi =(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
WifiInfoinfo = wifi.getConnectionInfo();
StringmacAdress = info.getMacAddress(); //獲取mac地址
intipAddress=info.getIpAddress();//獲取ip地址
Stringip=intToIp(ipAddress);
}
publicStringintToIp(inti)
{
return((i>>24)&0xFF)+"."+((i>>16)&0xFF)+"."
+((i>>8)&0xFF)+"."+(i&0xFF);
}
這里需要加入permission
<uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"/>
第二種方法:
調(diào)用android 的API:NetworkInterface. getHardwareAddress ()
首先是getLocalIpAddress,獲取本地IP地址.
//獲取本地IP
public static StringgetLocalIpAddress()
{
try {
for (Enumeration en =NetworkInterface
.getNetworkInterfaces(); en.hasMoreElements();)
{
NetworkInterface intf =en.nextElement();
for(Enumeration enumIpAddr = intf
.getInetAddresses();enumIpAddr.hasMoreElements();)
{
InetAddress inetAddress =enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()
&&!inetAddress.isLinkLocalAddress())
{
return inetAddress.getHostAddress().toString();
}
}
}
}catch (SocketException ex)
{
Log.e("WifiPreference IpAddress",ex.toString());
}
return null;
}
但如果沒有紅色部分代碼。該方法在android2.3, 2.2...較老版本有效,在android較新版本
(例如4.0等)獲取的數(shù)據(jù)不正確(我們這里增加了紅色部分后,可以支持4.0以上版本)
然后,再根據(jù)IP地址獲取到MAC地址:
public static StringgetLocalMacAddressFromIp(Context context)
{
String mac_s="";
try {
byte[]mac;
NetworkInterface ne =
NetworkInterface.getByInetAddress(InetAddress.getByName(getLocalIpAddress()));
mac = ne.getHardwareAddress();
mac_s =byte2hex(mac);
}catch (Exception e) {
e.printStackTrace();
}
return mac_s;
}
public staticString byte2hex(byte[]b)
{
StringBuffer hs =newStringBuffer(b.length);
String stmp ="";
int len =b.length;
for (int n = 0; n< len; n++)
{
stmp= Integer.toHexString(b[n] &0xFF);
if(stmp.length() == 1){
hs= hs.append("0").append(stmp);
}else {
hs= hs.append(stmp);
}
}
return String.valueOf(hs);
}
針對獲取IP地址的方法,還有一種改進(jìn)方法,這是是網(wǎng)上運(yùn)用比較多的,測試表明,該方法獲取到了類似fe80::b607:f9ff:fee5:487e..這樣的IP地址。注意看這里的IP地址是IPV6的地址形式。所以,一種解決方法是,在上面代碼中的最內(nèi)層的for循環(huán)的if語句中對inetAddress進(jìn)行格式判斷,只有其是IPV4格式地址時(shí),才返回值。修改后代碼如下:
public String getLocalIpAddress() {
try {
String ipv4;
List nilist =Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface ni:nilist)
{
List ialist =Collections.list(ni.getInetAddresses());
for (InetAddress address: ialist)
{
if (!address.isLoopbackAddress()&&
InetAddressUtils.isIPv4Address(ipv4=address.getHostAddress()))
{
return ipv4;
}
}
}
} catch (SocketException ex) {
Log.e(LOG_TAG, ex.toString());
}
return null;
}
愛華網(wǎng)



