Android general method to obtain mac address and Ethernet information ip address, gateway, dns, etc.

1. Some methods of obtaining the mac address

The first method: read the files under the sys/class/net/ path

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

However, if the above method does not release the read and write permissions of the file, it cannot be read;

Now introduce another method:

Method 2: Using ConnectivityManager

1. Get connected network information

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

The above is to obtain the network information object of the current connection. If you want to use it, you must judge the empty state of the object and the state of the connection.

You can print out all the current network connection information

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

2. Obtain the mac address (only in the case of Ethernet connection, wifi obtains the current wifi name)

 String extraInfo = activeNetworkInfo.getExtraInfo();

3. Obtain ip information

 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. Get the gateway address information:

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. Get dns information:

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: Get the subnet mask address

 /**
     * 获取子网掩码
     * @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";
    }

Call this method by getting the network port name

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

The above are general ways to obtain network information; both wifi and Ethernet can be used, you can try it;

Evening Breeze Through the Flower Garden

Guess you like

Origin blog.csdn.net/qq_33796069/article/details/127401634