6

如何获取通过以太网连接的 android 设备的 DhcpInfo()(网关 ip、网络掩码、dns 等)?

如果设备通过 Wifi 连接并使用 ACCESS_WIFI_STATE 权限,我知道如何获取它:

 WifiManager wifi = (WifiManager) context.getSystemService(Service.WIFI_SERVICE);
 DhcpInfo dhcp = wifi.getDhcpInfo();

但是如果设备通过以太网连接,我仍然找不到获取它的方法......谢谢

4

1 回答 1

6

在您的AndroidManifest.xml文件中

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

你的代码:

    ConnectivityManager connectivityManager = (ConnectivityManager) getApplicationContext().getSystemService(Service.CONNECTIVITY_SERVICE);

                /* you can print your active network via using below */
                Log.i("myNetworkType: ", connectivityManager.getActiveNetworkInfo().getTypeName());
                WifiManager wifiManager= (WifiManager) getApplicationContext().getSystemService(getApplicationContext().WIFI_SERVICE);


                Log.i("routes ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getRoutes().toString());
                Log.i("domains ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getDomains().toString());
                Log.i("ip address ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getLinkAddresses().toString());
                Log.i("dns address ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getDnsServers().toString());



                if(connectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI) {
                    Log.i("myType ", "wifi");
                    DhcpInfo d =wifiManager.getDhcpInfo();
                    Log.i("info", d.toString()+"");
                }
                else if(connectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_ETHERNET) {
/* there is no EthernetManager class, there is only WifiManager. so, I used this below trick to get my IP range, dns, gateway address etc */

                    Log.i("myType ", "Ethernet");
                    Log.i("routes ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getRoutes().toString());
                    Log.i("domains ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getDomains().toString());
                    Log.i("ip address ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getLinkAddresses().toString());
                    Log.i("dns address ", connectivityManager.getLinkProperties(connectivityManager.getActiveNetwork()).getDnsServers().toString());

                }
                else {

                }

输出 在此处输入图像描述

您无法知道您是通过 wifi 连接还是使用WifiManagerWifiManager与 wifi 交易的网络连接。你必须使用ConnectivityManager. 我再次更新了我合并的代码WifiManagerConnectivityManager产生了你想要的结果。

于 2017-09-06T01:43:16.990 回答