Obtaining your ip address on Android

March 28, 2010

With the verbosity (I mean that in a good way) of the Android APIs, you’d think that it would be extremely straightforward to get a handle on the ip address for your android device.  It’s not – but with the code below you can obtain this information in the most efficient possible way using some math to translate the returned integer from WifiInfo into it’s component string ip address.

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
String ip = intToIp(ipAddress);

....................

public String intToIp(int i) {
   return ((i >> 24 ) & 0xFF ) + "." +
               ((i >> 16 ) & 0xFF) + "." +
               ((i >> 8 ) & 0xFF) + "." +
               ( i & 0xFF) ;
}
Advertisements

3 Responses to “Obtaining your ip address on Android”


  1. That is a much slicker solution than others I’ve seen.

  2. German Castignani Says:

    Hi. In the correct ordering, the conversion is as follows:

    public String intToIp(int i) {

    return (( i & 0xFF) + “.”
    + ((i >> 8 ) & 0xFF) + “.”
    + ((i >> 16 ) & 0xFF) + “.”
    + ((i >> 24 ) & 0xFF ));

    }

  3. thens Says:

    So I assume the return value is stored as little endian, otherwise the first solution would be correct.
    Correct me if I’m wrong though, WifiInfo’s documentation does not state anything about the endianness.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: