1

从我的活动中,我试图获取我设备的 IP 地址。我正在使用以下代码来执行此操作:

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) {
            ex.printStackTrace();
        }
        return null;
    }

但是这个函数没有返回正确的 ip 地址(可能它返回的是路由器 ip,而不是为我的设备提供的代理 ip)。我在 StackOverflow 上经历了很多线程,但没有一个有帮助。

另外,我不打算使用:

WifiManager wifiMan = (WifiManager) this.getSystemService(this.WIFI_SERVICE);
        WifiInfo wifiInf = wifiMan.getConnectionInfo();
        int ipAddress = wifiInf.getIpAddress();

在某些情况下,我的设备是有线连接的,而不是无线的

有人可以建议我如何从代码中获取设备的正确 IP 地址吗?

理想情况下,我希望设备是有线/无线连接的,它应该提供设备的正确 IP 地址。在某些情况下,我的设备是有线连接的。

谢谢你的帮助。

4

0 回答 0