相关疑难解决方法(0)

37
推荐指数
4
解决办法
7万
查看次数

使用 InetAddress 类中的 getHostAddress() 以编程方式获取默认网关

我想以编程方式在 Android 中获取默认网关。我首先找到了以下解决方案:@Sandeep 回答的代码中路由器的 IP 地址

然后我意识到formatIpAddress已被弃用。如文档所述:我们可以getHostAddress()

我还认为,这更好,因为我可能不需要像@Sandeep 在他的回答中提到的那样为我的应用程序添加新权限:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
Run Code Online (Sandbox Code Playgroud)

我使用了以下解决方案get default gateway,例如:How to get default gateway using Ethernet, not wifi

public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        return inetAddress.getHostAddress();
                    }
                }
            }
        } catch (SocketException ex) …
Run Code Online (Sandbox Code Playgroud)

ip android gateway tcp-ip

6
推荐指数
0
解决办法
2719
查看次数

标签 统计

android ×2

gateway ×1

ip ×1

ip-address ×1

networking ×1

tcp-ip ×1