获取Mac地址实际项目中测试了如下几种方法:
(1)设备开通Wifi连接,获取到网卡的MAC地址(但是不开通wifi,这种方法获取不到Mac地址,这种方法也是网络上使用的最多的方法)

//根据Wifi信息获取本地Mac
public static String getLocalMacAddressFromWifiInfo(Context context){
WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
return info.getMacAddress();
}

(2)调用Linux的busybox,通过linux命令来获取

//根据busybox获取本地Mac
public static String getLocalMacAddressFromBusybox(){
String result = "";
String Mac = "";
result = callCmd("busybox ifconfig","HWaddr"); //如果返回的result == null,则说明网络不可取
if(result==null){
return "网络出错,请检查网络";
} //对该行数据进行解析
//例如:eth0 Link encap:Ethernet HWaddr 00:16:E8:3E:DF:67
if(result.length()> && result.contains("HWaddr")==true){
Mac = result.substring(result.indexOf("HWaddr")+, result.length()-);
Log.i("test","Mac:"+Mac+" Mac.length: "+Mac.length()); /*if(Mac.length()>1){
Mac = Mac.replaceAll(" ", "");
result = "";
String[] tmp = Mac.split(":");
for(int i = 0;i<tmp.length;++i){
result +=tmp[i];
}
}*/
result = Mac;
Log.i("test",result+" result.length: "+result.length());
}
return result;
} private static String callCmd(String cmd,String filter) {
String result = "";
String line = "";
try {
Process proc = Runtime.getRuntime().exec(cmd);
InputStreamReader is = new InputStreamReader(proc.getInputStream());
BufferedReader br = new BufferedReader (is); //执行命令cmd,只取结果中含有filter的这一行
while ((line = br.readLine ()) != null && line.contains(filter)== false) {
//result += line;
Log.i("test","line: "+line);
} result = line;
Log.i("test","result: "+result);
}
catch(Exception e) {
e.printStackTrace();
}
return result;
}

(3)调用Android 的API: NetworkInterface. getHardwareAddress ()
该API的level为9,只有android 2.3以上才有该接口

//根据IP获取本地Mac
public static String getLocalMacAddressFromIp(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 static String byte2hex(byte[] b) {
StringBuffer hs = new StringBuffer(b.length);
String stmp = "";
int len = b.length;
for (int n = ; n < len; n++) {
stmp = Integer.toHexString(b[n] & 0xFF);
if (stmp.length() == )
hs = hs.append("").append(stmp);
else {
hs = hs.append(stmp);
}
}
return String.valueOf(hs);
}

其中getLocalIpAddress是获取本地IP地址

//获取本地IP
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) {
Log.e("WifiPreference IpAddress", ex.toString());
} return null;
}

获取本地IP地址
在网络上搜索一下,一般就有如下的代码:

//获取本地IP
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) {
Log.e("WifiPreference IpAddress", ex.toString());
} return null;
}

但是经过测试该方法在android2.3, 2.2...较老版本有效,但是在android较新版本(例如4.0等)获取的数据不正确。
获取到了类似fe80::b607:f9ff:fee5:487e..这样的IP地址。经过一番努力,终于找出原因。
上面的IP地址是IPV6的地址形式(大概这个意思,具体没有太深入研究)。解决方法是,在上面代码中的最内层的for循环的if语句中对inetAddress进行格式判断,只有其是IPV4格式地址时,才返回值。修改后代码如下:(下面的方法也是网络上的方法,没有结果验证)

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;
}

网络上还有一种方法来获取本地IP地址(不过是在wifi状态下)
通过WifiManager, DhcpInfo获取IP地址以及网关等信息(在android4.0等版本也适用)

package com.jason.demo.androidip;  

import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.text.format.Formatter; public class IPAddress { public String getIPAddress(Context ctx){
WifiManager wifi_service = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcpInfo = wifi_service.getDhcpInfo();
WifiInfo wifiinfo = wifi_service.getConnectionInfo();
System.out.println("Wifi info----->"+wifiinfo.getIpAddress());
System.out.println("DHCP info gateway----->"+Formatter.formatIpAddress(dhcpInfo.gateway));
System.out.println("DHCP info netmask----->"+Formatter.formatIpAddress(dhcpInfo.netmask));
//DhcpInfo中的ipAddress是一个int型的变量,通过Formatter将其转化为字符串IP地址
return Formatter.formatIpAddress(dhcpInfo.ipAddress);
}
}

加入permission
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

不过我自己在做项目过程中,用另外一种方法也解决了android4.0获取IP错误的问题:

//获取本地IP
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() && !inetAddress.isLinkLocalAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
Log.e("WifiPreference IpAddress", ex.toString());
} return null;
}

参考博文:

http://www.cnblogs.com/Amandaliu/archive/2011/11/06/2238177.html
Android获取Mac地址

http://blog.csdn.NET/ccf0703/article/details/7451274
解决安卓4.0获取本地IP地址问题。

http://blog.csdn.Net/garybook/article/details/7874456
通过WifiManager,DhcpInfo获取android IP地址及网关等信息(两种方式)

http://blog.csdn.net/lizzydarcymsp/article/details/5623302
利用InetAddress类确定特殊IP地址 (isLinkLocalAddress,isLoopbackAddress等)

转自:http://www.cnblogs.com/lijunamneg/archive/2013/03/04/2943146.html

然后我自己弱弱说一句, 我用前面两种方法的时候有空指针,最后采取的本地IP获取mac地址。

android获取Mac地址和IP地址的更多相关文章

  1. android获取本机的IP地址和mac物理地址

    /获取本机IP地址 public String getLocalIpAddress() { WifiManager wifiManager = (WifiManager) getSystemServi ...

  2. iOS 获取设备信息,mac地址,IP地址,设备名称

    #import "DeviceInfoUtil.h" #import "GlobleData.h" #import "sys/utsname.h&qu ...

  3. 获取客户端网卡MAC地址和IP地址实现JS代码

    获取客户端网卡MAC地址和IP地址实现JS代码 作者: 字体:[增加 减小] 类型:转载   获取客户端的一些信息,如IP和MAC,以结合身份验证,相信很多人都会这样做吧,我们这里用Javascrip ...

  4. c#中如何获取本机MAC地址、IP地址、硬盘ID、CPU序列号等系统信息

    我们在利用C#开发桌面程序(Winform)程序的时候,经常需要获取一些跟系统相关的信息,例如用户名.MAC地址.IP地址.硬盘ID.CPU序列号.系统名称.物理内存等. 首先需要引入命名空间: us ...

  5. js获取本机mac地址,IP地址,计算机名

    <!DOCTYPE HTML> <html> <head> <title>js获取本机mac地址,IP地址,计算机名</title> < ...

  6. c#中如何获取本机用户名、MAC地址、IP地址、硬盘ID、CPU序列号、系统名称、物理内存

    我们在利用C#开发桌面程序(Winform)程序的时候, 经常需要获取一些跟系统相关的信息, 以下这些代码获取能有些用处. c#中如何获取本机用户名.MAC地址.IP地址.硬盘ID.CPU序列号.系统 ...

  7. Android 手机上获取手机当前上网IP地址

      [转] 原文              Android 手机上获取手机当前上网IP地址                (手机网关给手机号分配的IP) 每个手机上网通过移动网关的时候,网关都会给该手 ...

  8. iphone开发之获取网卡的MAC地址和IP地址

    本文转载至 http://blog.csdn.net/arthurchenjs/article/details/6358489 这是获取网卡的硬件地址的代码,如果无法编译通过,记得把下面的这几个头文件 ...

  9. 获取本机的IP地址和mac地址

    1. 以前一直用ipconfig来查看ip地址,哈哈哈,现在发现挺好玩 #获取本机的IP地址和mac地址 import uuid import socket def get_mac_address() ...

随机推荐

  1. OA学习笔记-002-Sruts2.1配置

    一.jar commons-fileupload-1.2.1.jarcommons-io-1.3.2.jarfreemarker-2.3.15.jarognl-2.7.3.jarstruts2-cor ...

  2. 值得推荐的C/C++框架和库 very good

    [本文系外部转贴,原文地址:http://coolshell.info/c/c++/2014/12/13/c-open-project.htm]留作存档 下次造轮子前先看看现有的轮子吧 值得学习的C语 ...

  3. Android用户界面 UI组件--TextView及其子类(五) DigitalClock,AnalogClock,RadioButton,CheckBox,ToggleButton汇总

    DigitalClock和AnalogClock两个时钟类 可以为DigitalClock设置背景图片,自定义时针,秒针,分针的样式 例子: <?xml version="1.0&qu ...

  4. Win7资源管理器已停止工作——StackHash_6c37,R6205错误

      2013-9-20 此问题由来已久,截图及"问题签名"如下: 问题签名: 问题事件名称: BEX64 应用程序名: Explorer.EXE 应用程序版本: 6.1.7601. ...

  5. Oracle DBMS_SESSION

    Version 11.1   General Purpose Try dbms_session.reset_package. This call will reset all packages var ...

  6. 使用GDI+轻松创建缩略图

    Gdi+ 还是相当好用的. 1> Image保存图像,需要一个CLSID的参数,它可以这样获得: int   GetEncoderClsid(const   WCHAR*   format,   ...

  7. loadrunner 与Md5

    loadrunner 与Md5 1.新建个c vuser脚本 2.把cmd5.h导入脚本 3.在脚本中,引入cmd5.h,可以在action前面加个void,但要屏蔽return 来自为知笔记(Wiz ...

  8. 基于.NET平台的分层架构实战(六)——依赖注入机制及IoC的设计与实现[转]

    原文:http://www.cnblogs.com/leoo2sk/archive/2008/06/19/1225223.html 我们设计的分层架构,层与层之间应该是松散耦合的.因为是单向单一调用, ...

  9. apache的FileUtils方法大全

    FileUtils 获取系统的临时目录路径:getTempDirectoryPath() [java] view plaincopyprint? public static String getTem ...

  10. 开发服务器端——工程配置

    概述:    服务器开发,一般分为 主程序类Project(主函数main) 流程控制类Kernel(处理收到的数据) 网络类Network(数据的收发) 公共类Common(定义一些常量和结构体,自 ...