Showing posts with label IP address. Show all posts

Detect IP Address of device when network change detected

When network change is detected whether it is wifi to mobile network or mobile network to wifi, the IP address allocated to device is changed.

1 . If network changes from wifi to mobile data then you can find the new IP 
     address allocated to device by writing the following code


try {
    for (Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces();
 enumeration.hasMoreElements();) 
    {
        NetworkInterface nInterface = enumeration.nextElement();
        for (Enumeration<InetAddress> enumIpAddresses = nInterface.getInetAddresses(); 
             enumIpAddresses.hasMoreElements();) 
        {
            InetAddress inetAddress = enumIpAddresses.nextElement();
            if (!inetAddress.isLoopbackAddress()) 
            {
                return inetAddress.getHostAddress().toString();
            }
        }
    }
} catch (Exception ex) {
      ex.printStackTrace();
}
 
2 . If network changes from mobile data to wifi then you can find the new IP
     address allocated to device by writing  the following code.

WifiManager wifiManager=(WifiManager)context.getSystemService(Context.WIFI_SERVICE);
String ipAddress=Formatter.formatIpAddress(wifiManager.getConnectionInfo().getIpAddress());