Every android device has a local ip address and we can easily get that ip address for our backend purpose like we can save that ip address to our server.
In below method NetworkInterface is a interface that provides many methods to get device network informations like to get human readable name, hardware address etc.
where InetAddress is used to provide methods to get host address that may be a IPV4 or IPV6.
public String checkLocalIpAddress()
{
try {
for (Enumeration<NetworkInterface> enumeration = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface networkInterface = enumeration.nextElement();
for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (Exception e) {
Log.e("exception found", e.toString());
}
return null;
}
Add below permission in the manifest file.
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
0 Comment(s)