0

My android app cannot get its own NetworkInterface from its IP address (getByInetAddress). Every other step of the process (get Wifi Info, get Wifi IP) works, but the last step (getting a handle to the actual Network Interface from its IP address) fails.

I added some output to locate the exact moment the problems occurs. Here's what I observe:

D/WIFI_ME: Manager Status: 3
D/WIFI_ME: wifiInfo: 503425216
D/WIFI_ME: wifiIPbytes: [B@285190e
D/WIFI_ME: netAddr: /30.1.168.192
D/WIFI_ME: wifiInterface: null

I checked my router, 192.168.1.30 is the correct address for this interface. I checked the permissions, my app has:

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

And here is the actual code:

WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
    Log.d("WIFI_ME", "Manager Status: " + wifiManager.getWifiState());
    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
    Log.d("WIFI_ME", "wifiInfo: " + wifiInfo.getIpAddress());
    int wifiIP = wifiInfo.getIpAddress();
    byte[] wifiIPbytes = BigInteger.valueOf(wifiIP).toByteArray();
    Log.d("WIFI_ME", "wifiIPbytes: " + wifiIPbytes.toString());
    try{
        InetAddress netAddr = InetAddress.getByAddress(wifiIPbytes);
        Log.d("WIFI_ME", "netAddr: " + InetAddress.getByAddress(wifiIPbytes));
        wifiInterface = NetworkInterface.getByInetAddress(netAddr);
        Log.d("WIFI_ME", "wifiInterface: " + NetworkInterface.getByInetAddress(netAddr));
    }
    catch(UnknownHostException ex){
        Log.e("WIFI_ME", ex.getMessage());
        ex.printStackTrace();
    }
    catch(SocketException ex){
        Log.e("WIFI_ME", ex.getMessage());
        ex.printStackTrace();
    }

I expect the wifiInterface = NetworkInterface.getByInetAddress(netAddr); to find the actual Network Interface, as documented here: https://developer.android.com/reference/java/net/NetworkInterface#getByInetAddress(java.net.InetAddress)

Eric
  • 477
  • 3
  • 17
  • It is null because the IP address is not correctly retrieved. You need to aware of the endianness can vary on different hardware when retrieving the byte array from the integer result of `wifiInfo.getIpAddress()`. In your case, it is obvious that the correct IP address is "192.168.1.30". But, due to the endian issue, you get "30.1.168.192". Refer this: https://stackoverflow.com/questions/16730711/get-my-wifi-ip-address-android/16732477 – ecle Jan 23 '19 at 16:12
  • This worked. I noticed the bytes were reversed, but did not realized this wasn't the expected behavior. Many thanks! – Eric Jan 24 '19 at 08:43

0 Answers0