Search code examples
androidandroid-wificonnectivity

getIpAddress() method returns integer representation of IPv4?


In the below code i am tryin to get the IP of he network, but wht i get from info.getIpAddress(); is

-25576378

why? and what is this?

Code

WifiInfo info = mWiFiMgr.getConnectionInfo();
String ssid;
int strength = WifiManager.calculateSignalLevel(info.getRssi(), 5);
String unit = WifiInfo.LINK_SPEED_UNITS;
int ip_add = info.getIpAddress();
int speed = info.getLinkSpeed();

Solution

  • You can use this method to get the ip string:

    private static String getIpAddress(WifiInfo wifiInfo) {
        String result;
        int ip = wifiInfo.getIpAddress();
    
        result = String.format("%d.%d.%d.%d", (ip & 0xff), (ip >> 8 & 0xff), (ip >> 16 & 0xff),
                (ip >> 24 & 0xff));
    
        return result;
    }
    

    wifiInfo.getIpAddress() returns an integer. This is possible, because an IPv4-address contains 4 bytes (f.e. 192.168.255.2 ==> 4 times 1 byte), just like an integer consumes 4 byte in Java/Android. By shifting the given integer number, you can determine each of the ip's byte values.