在Android设备上查找netMask

时间:2016-10-15 11:53:13

标签: android networking network-programming

我必须找到有关Android设备所连接网络的信息。 Android设备基本上是Android电视,它具有WiFi和以太网连接 我正在使用WiFi并获取除netMask以外的所有正确信息,因为它始终显示 0 (零),而它应显示 255.255.255.0

以下是我正在使用的代码:

wifiMgr= (WifiManager) getSystemService(Context.WIFI_SERVICE);
dhcpInfo=wifiMgr.getDhcpInfo();

vDns1="DNS 1: "+intToIp(dhcpInfo.dns1);
vDns2="DNS 2: "+intToIp(dhcpInfo.dns2);
vGateway="Default Gateway: "+intToIp(dhcpInfo.gateway);
vIpAddress="IP Address: "+intToIp(dhcpInfo.ipAddress);
vLeaseDuration="Lease Time: "+String.valueOf(dhcpInfo.leaseDuration);
vNetmask="Subnet Mask: "+intToIp(dhcpInfo.netmask);
vServerAddress="Server IP: "+intToIp(dhcpInfo.serverAddress);

intToIp(int)的定义:

public String intToIp(int i) {

    return ((i >> 24 ) & 0xFF ) + "." +
            ((i >> 16 ) & 0xFF) + "." +
            ((i >> 8 ) & 0xFF) + "." +
            ( i & 0xFF) ;
}

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />

为什么会发生这种情况,我该如何解决?

1 个答案:

答案 0 :(得分:4)

这是an android bug

根据错误报告,您可以使用以下解决方法(从报告中复制):

WifiManager wifiManager = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcpInfo = wifiManager.getDhcpInfo();
try {
    InetAddress inetAddress = InetAddress.getByAddress(extractBytes(dhcpInfo.ipAddress));
    NetworkInterface networkInterface = NetworkInterface.getByInetAddress(inetAddress);
    for (InterfaceAddress address : networkInterface.getInterfaceAddresses()) {
        //short netPrefix = address.getNetworkPrefixLength();
        Log.d(TAG, address.toString());
    }
} catch (IOException e) {
    Log.e(TAG, e.getMessage());
}

...或完全停止使用此API,而是使用LinkProperties API。