获取设备的IP地址

时间:2015-08-13 14:46:50

标签: android android-wifi android-tv android-wireless

从我的活动中,我正在尝试获取设备的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地址。在某些情况下,我的设备是有线连接的。

感谢您的帮助。

0 个答案:

没有答案
相关问题