Hello I am using the code below to get IP address of android device,
private String returnIPAdrress()
{
String IPAddress = null;
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())
{
IPAddress = inetAddress.getHostAddress().toString();
}
}
}
}
catch (SocketException ex)
{
Log.e("ServerActivity", ex.toString());
return null;
}
return IPAddress;
}
When i test it on Galaxy tablet(os=2.3) it works fine and gives me valid IP address.
I have test it on emulator(os=2.2) and it gives me IP address as 10.0.2.15 which is also valid i guess.
But when run it on Micromax canvas(os=4.1) it gives me IP address as fe80::d0b3:3fff:fe9d:f68c%p2p0 which is wrong.
is it because of different OS version?
How can i solve this?
Try this method:
public static String getIPAddress() {
try {
List<NetworkInterface> interfaces = Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface intf : interfaces) {
List<InetAddress> addrs = Collections.list(intf.getInetAddresses());
for (InetAddress addr : addrs) {
if (!addr.isLoopbackAddress()) {
String sAddr = addr.getHostAddress().toUpperCase();
boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
if (isIPv4 && intf.getDisplayName().startsWith("wlan")) {
return sAddr;
}
}
}
}
} catch (Exception ex) {
return null;
}
return null;
}
You can access IP address of a device using dhcp.ipaddress
private final WifiManager manager;
private final DhcpInfo dhcp;
private InetAddress getMyIP() {
manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
dhcp = manager.getDhcpInfo();
final String address = Formatter.formatIpAddress(dhcp.ipAddress); // ipAddress - IP address of my device, assigned through dhcp
InetAddress myIP = null;
try {
myIP = InetAddress.getByName(address);
Log.i("My IP "," + myIP.toString());
} catch (Exception e) {
Log.e("Cannot find my own IP. Error ", e.toString());
}
return myIP;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.