Android Get Mobile IP Address code example

Android Get Mobile IP Address

Getting the android IP address for Wi-Fi connection using the API is very simple:

Android Get Mobile IP Address Code Example

Android Get Mobile IP Address :

/**
 * Get the IP of current Wi-Fi connection
 * @return IP as string
 */
private String getIP() {
 try {
   WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
   WifiInfo wifiInfo = wifiManager.getConnectionInfo();
   int ipAddress = wifiInfo.getIpAddress();
   return String.format(Locale.getDefault(), "%d.%d.%d.%d",
   (ipAddress & 0xff), (ipAddress >> 8 & 0xff),
   (ipAddress >> 16 & 0xff), (ipAddress >> 24 & 0xff));
 } catch (Exception ex) {
   Log.e(TAG, ex.getMessage());
   return null;
 }
}

But what if you need to get the Mobile connection IP?

The answer is to check the NetWorkInterface like this:

/** Get IP For mobile */
public static String getMobileIP() {
  try {
    for (Enumeration<NetworkInterface> en = NetworkInterface
    .getNetworkInterfaces(); en.hasMoreElements();) {
       NetworkInterface intf = (NetworkInterface) en.nextElement();
       for (Enumeration<InetAddress> enumIpAddr = intf
          .getInetAddresses(); enumIpAddr.hasMoreElements();) {
          InetAddress inetAddress = enumIpAddr.nextElement();
          if (!inetAddress.isLoopbackAddress()) {
             String ipaddress = inetAddress .getHostAddress().toString();
             return ipaddress;
          }
       }
    }
  } catch (SocketException ex) {
     Log.e(TAG, "Exception in Get IP Address: " + ex.toString());
  }
  return null;
}

And if you want to get the IP as IPV4 just replace the line:

          if (!inetAddress.isLoopbackAddress()) {

With:

 if (!inetAddress.isLoopbackAddress() && InetAddressUtils.isIPv4Address(inetAddress.getHostAddress())) {

1 thought on “Android Get Mobile IP Address code example

  1. aa

    Hi, thanks for your post. How do you check the v4 IP in your InetAddressUtils.isIPv4Address? Just an instance check with Inet4Address or some additional checks? Missing the source here.. :-/

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.