Reputation: 7028
I have problem with android 4.0.3. I'm using the method below to get local IP:
public static String getLocalIpAddress() {
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {
return inetAddress.getHostAddress().toString();
}
}
}
} catch (SocketException ex) {
ex.printStackTrace();
}
return null;
}
It works great on android v2.1-2.3. But on emulator with android 4.0.3 it returns something like mac-address: fe80::fad0:bdff:fe4d:4871 Can anyone explain what's happened?
Upvotes: 0
Views: 2098
Reputation: 46
To get only the IPv4 address, change
if (!inetAddress.isLoopbackAddress()) {
to
if (!inetAddress.isLoopbackAddress() && (inetAddress instanceof Inet4Address)) {
Upvotes: 3
Reputation: 12375
You might be better off using getAllByName
.
As I mentioned , the address you are getting is an IPv6 address & you cant convert an IPv6 address to an IPv4 address.
Upvotes: 0