gpt4 book ai didi

android - Android 上的 ifconfig 和 route 命令

转载 作者:太空宇宙 更新时间:2023-11-04 12:41:25 24 4
gpt4 key购买 nike

我想知道是否存在以编程方式在 Android 设备中获取 ifconfigroute 命令结果的方法?我可以在非 root 设备上执行此操作吗?

最佳答案

在你的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

您无法知道您是通过 wifi 连接还是使用 WifiManager 进行网络连接,因为 WifiManager 仅处理 wifi。您必须使用 ConnectivityManager。我再次更新了代码,合并了 WifiManagerConnectivityManager 以产生您想要的结果。

关于android - Android 上的 ifconfig 和 route 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40091226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com