Android通用方法获取mac地址和以太网信息ip地址、网关、dns等

1.关于获取mac地址的一些方法

第一种方法:读取sys/class/net/路径下的文件

FileInputStream fis_name = null;
        FileInputStream fis = null;
        try {
//interfaceName 可以直接填写 eth0
            String path = "sys/class/net/"+interfaceName+"/address";
            fis_name = new FileInputStream(path);
            byte[] buffer_name = new byte[1024 * 8];
            int byteCount_name = fis_name.read(buffer_name);
            if (byteCount_name > 0) {
                mac = new String(buffer_name, 0, byteCount_name, "utf-8");
            }
            if (mac.length() == 0) {
                path = "sys/class/net/eth0/wlan0";
                fis = new FileInputStream(path);
                byte[] buffer = new byte[1024 * 8];
                int byteCount = fis.read(buffer);
                if (byteCount > 0) {
                    mac = new String(buffer, 0, byteCount, "utf-8");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(fis_name != null){
                try {
                    fis_name.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

可是上面的方法如果没有放开该文件的读写权限,是读取不到的;

现在介绍另外一种方法:

方法2:采用ConnectivityManager

1.获取连接的网络信息

ConnectivityManager cm = (ConnectivityManager) context.getApplicationContext().getSystemService(Service.CONNECTIVITY_SERVICE);
 NetworkInfo activeNetworkInfo = cm.getActiveNetworkInfo();

上面是获取当前连接的网络信息对象,如果要使用它,一定要对该对象进行判空和连接的状态判断

可以将当前的网络连接信息全部打印出来

if(activeNetworkInfo != null && activeNetworkInfo.isConnected()){
    Log.i("NetworkInfo info  : " +cm.getLinkProperties(cm.getActiveNetwork()).toString() );
}

2.获取mac地址(仅以太网连接的情况下,wifi获取的是当前的wifi名称)

 String extraInfo = activeNetworkInfo.getExtraInfo();

3.获取ip信息

 List<LinkAddress> linkAddresses = cm.getLinkProperties(cm.getActiveNetwork()).getLinkAddresses();
//获取当前连接的网络ip地址信息
if(linkAddresses != null && !linkAddresses.isEmpty()){
//注意:同时可以查看到两个网口的信息,但是ip地址不是固定的位置(即下标)
//所以遍历的时候需要判断一下当前获取的ip地址是否符合ip地址的正则表达式
 for (int i = 0; i < linkAddresses.size(); i++) {
     InetAddress address = linkAddresses.get(i).getAddress();
//判断ip地址的正则表达
     if(isCorrectIp(address.getHostAddress())){
       Log.i("ip地址"+address.getHostAddress())
         }
     }
 }                                   

4.获取网关地址信息:

List<RouteInfo> routes = cm.getLinkProperties(cm.getActiveNetwork()).getRoutes();
  if(routes != null && !routes.isEmpty()){
  for (int i = 0; i < routes.size(); i++) {
    //和ip地址一样,需要判断获取的网址符不符合正则表达式
     String hostAddress = routes.get(i).getGateway().getHostAddress();
     if(isCorrectIp(hostAddress)){
     Log.i("网关信息:" + hostAddress);
        }
     }
}

5.获取dns信息:

List<InetAddress> dnsServers = cm.getLinkProperties(cm.getActiveNetwork()).getDnsServers();
                if(dnsServers != null && dnsServers.size() >= 2){
                       Log.i("dns1 " + dnsServers.get(0).toString());
                    Log.i("dns2 " + dnsServers.get(1).toString());
                }

6:获取子网掩码地址

 /**
     * 获取子网掩码
     * @param interfaceName
     * @return
     */
    public static String getIpAddressMaskForInterfaces(String interfaceName) {
        //"eth0"
        try {
            //获取本机所有的网络接口
            Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
            //判断 Enumeration 对象中是否还有数据
            while (networkInterfaceEnumeration.hasMoreElements()) {
                //获取 Enumeration 对象中的下一个数据
                NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement();
                if (!networkInterface.isUp() && !interfaceName.equals(networkInterface.getDisplayName())) {
                    //判断网口是否在使用,判断是否时我们获取的网口
                    continue;
                }

                for (InterfaceAddress interfaceAddress : networkInterface.getInterfaceAddresses()) {
                    if (interfaceAddress.getAddress() instanceof Inet4Address) {
                        //仅仅处理ipv4
                        //获取掩码位数,通过 calcMaskByPrefixLength 转换为字符串
                        return calcMaskByPrefixLength(interfaceAddress.getNetworkPrefixLength());
                    }
                }
            }
        } catch (SocketException e) {
            e.printStackTrace();
       
        }

        return "0.0.0.0";
    }

通过获取网口名调用该方法

getIpAddressMaskForInterfaces(cm.getLinkProperties(cm.getActiveNetwork()).getInterfaceName())

以上则是通用获取网络信息的方式;wifi和以太网都可以用,可以试一下;

晚风过花庭

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>