I'm trying to get my cell phone ip address by using WifiManager and WifiInfo classes.
It returns correct ip address reversed.
public String getWifiIpAddress() {
WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wi = wm.getConnectionInfo();
byte[] ipAddress = BigInteger.valueOf(wi.getIpAddress()).toByteArray();
try {
InetAddress myAddr = InetAddress.getByAddress(ipAddress);
String hostAddr = myAddr.getHostAddress();
return hostAddr;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
result : 73.0.168.192
We can use the getLocalHost() static method of the InetAddress class to obtain the localhost IP address.
1) Get the local host address by calling getLocalHost() method of InetAddress class. 2) Get the IP address by calling getHostAddress() method.
InetAddress class is Java's encapsulation of an IP address. It is used by most of the other networking classes, including Socket , ServerSocket , URL , DatagramSocket , DatagramPacket , and more. public final class InetAddress extends Object implements Serializable.
An IP address is represented by 32-bit or 128-bit unsigned number. An instance of InetAddress represents the IP address with its corresponding host name. There are two types of addresses: Unicast and Multicast.
Ok, I just saw that your address is reversed! :)
It is referred as big/little endian issue, read more about Endianness which is must-to-know for all programmers, specially when doing applications integrations and migrations on different Operating Systems.
Add this after gettting the Connection Info from the Wifi manager.
int ipAddress = wi.getIpAddress();
ipAddress = (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) ?
Integer.reverseBytes(ipAddress) : ipAddress;
Then continue your code with toByteArray and getHostAddress etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With