Android-NetworkInterface与WifiManager

时间:2018-11-19 12:24:58

标签: android

我正在尝试显示所连接网络(WiFi /以太网)的IP地址。我混淆了两个IP地址。我可以看到两种方法。使用WiFi信息获取IP,并使用NetworkInterface获取IP。但是我得到了两个不同的IP。我需要使用哪一个。请让我知道。

使用NetworkInterface:

private void getIpUsingNetworkInterface() {
        String ipAddress = null;
        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()) {
                        ipAddress = inetAddress.getHostAddress().toString();
                    }
                }
            }
            Log.i("ipaddress==> ", "" + ipAddress);

            Log.i("", "");
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

使用WifiManager:

private void getIPUsingWiFiManager() {
        final WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        byte[] myIPAddress = BigInteger.valueOf(wifiInfo.getIpAddress()).toByteArray();
        InetAddress myInetIP = InetAddress.getByAddress(reverseByte(myIPAddress));
        String ipAddress = myInetIP.getHostAddress();
    }

我也可以从DhcpInfo获取IP地址。

DhcpInfo dhcp = wifiManager.getDhcpInfo();
String ipAddress = dhcp.ipAddress;

请告诉我哪种是获取连接网络IP地址的最佳和正确方法。

0 个答案:

没有答案