Find netMask on Android device
android, java, network-programming, networking
Solution
It's an android bug.
According to the bug report, you can either use the following workaround (copied from the report):
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());
}
... or stop using this API altogether and use the LinkProperties API instead.
Problem
I have to find information about the network to which the Android device is connected. Basically the Android device is a Android TV and it has WiFi and Ethernet connectivity. I am working with WiFi and getting all the correct information except `netMask` as it is always showing 0 (zero), whereas it should show 255.255.255.0 Following is the code that I'm using: ``` 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); ``` Definition for `intToIp(int)`: ``` public String intToIp(int i) { return ((i >> 24 ) & 0xFF ) + "." + ((i >> 16 ) & 0xFF) + "." + ((i >> 8 ) & 0xFF) + "." + ( i & 0xFF) ; } ``` The `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" /> ``` Why is this happening and how can I fix it?