通过以太网连接Android DhcpInfo

时间:2017-09-06 00:42:22

标签: android networking wifimanager android-connectivitymanager

如何通过以太网连接Android设备的DhcpInfo()(网关ip,netmask,dns等)?

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

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

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

1 个答案:

答案 0 :(得分:2)

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 {

                }

<强>输出 enter image description here

您无法通过使用WifiManager来了解您是通过wifi还是网络连接,因为WifiManager仅处理wifi。您必须使用ConnectivityManager。我在合并WifiManagerConnectivityManager的位置再次更新了代码,以生成您想要的结果。