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

本文介绍了两种获取MAC地址的方法:一是通过`sys/class/net`目录下的文件系统,需确保权限;二是利用ConnectivityManager服务,适用于获取当前活跃网络的MAC地址,包括以太网和Wi-Fi。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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和以太网都可以用,可以试一下;

晚风过花庭

以下是一个获取以太网信息的示例代码: ``` public class EthernetInfoActivity extends AppCompatActivity { private TextView tvIpMode; private TextView tvIpAddress; private TextView tvGateway; private TextView tvSubnetMask; private TextView tvDns1; private TextView tvDns2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_ethernet_info); tvIpMode = findViewById(R.id.tv_ip_mode); tvIpAddress = findViewById(R.id.tv_ip_address); tvGateway = findViewById(R.id.tv_gateway); tvSubnetMask = findViewById(R.id.tv_subnet_mask); tvDns1 = findViewById(R.id.tv_dns1); tvDns2 = findViewById(R.id.tv_dns2); // 获取以太网管理器 EthernetManager ethernetManager = (EthernetManager) getSystemService(Context.ETHERNET_SERVICE); // 获取IP模式 int ipMode = ethernetManager.getEthernetMode(); if (ipMode == EthernetManager.ETHERNET_CONNECT_MODE_DHCP) { tvIpMode.setText("DHCP"); } else if (ipMode == EthernetManager.ETHERNET_CONNECT_MODE_MANUAL) { tvIpMode.setText("静态IP"); } // 获取IP地址网关、子网掩码、DNS EthernetDevInfo devInfo = ethernetManager.getSavedEthernetDevInfo(); if (devInfo != null) { tvIpAddress.setText(devInfo.getIpAddress()); tvGateway.setText(devInfo.getRouteAddr()); tvSubnetMask.setText(devInfo.getNetMask()); tvDns1.setText(devInfo.getDnsAddr()); tvDns2.setText(devInfo.getDns2Addr()); } } } ``` 在布局文件中,我们需要添加相应的TextView: ``` <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="IP模式:" /> <TextView android:id="@+id/tv_ip_mode" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="IP地址:" /> <TextView android:id="@+id/tv_ip_address" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="网关地址:" /> <TextView android:id="@+id/tv_gateway" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="子网掩码:" /> <TextView android:id="@+id/tv_subnet_mask" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="首选DNS:" /> <TextView android:id="@+id/tv_dns1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:padding="16dp"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="备选DNS:" /> <TextView android:id="@+id/tv_dns2" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> ``` 运行该示例代码将会显示以太网IP模式、IP地址网关地址、子网掩码、首选DNS、备选DNS
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值