设为首页 收藏本站
查看: 1868|回复: 0

[经验分享] android获取Mac地址和IP地址

[复制链接]

尚未签到

发表于 2017-7-5 12:42:38 | 显示全部楼层 |阅读模式
  获取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()>0 && result.contains("HWaddr")==true){
Mac = result.substring(result.indexOf("HWaddr")+6, result.length()-1);
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;
}
}*/
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 = 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);
}
  其中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
  然后我自己弱弱说一句, 我用前面两种方法的时候有空指针, DSC0000.jpg 最后采取的本地IP获取mac地址。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-390880-1-1.html 上篇帖子: mac 安装mysql + 修改root用户密码 + 及报Access denied for user 'root'@'localhost' (using pa 下篇帖子: Mac os JAVA 开发环境配置简述
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表