Detect IP Address of device when network change detected

Friday, January 20, 2017 Unknown 0 Comments

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());

0 comments: