Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getHostAddress() returns a reversed ip address

Tags:

java

android

ipv4

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

like image 670
Bana Avatar asked Apr 29 '15 07:04

Bana


People also ask

Which method is used to return the IP address of local machine?

We can use the getLocalHost() static method of the InetAddress class to obtain the localhost IP address.

How do I return an IP address in Java?

1) Get the local host address by calling getLocalHost() method of InetAddress class. 2) Get the IP address by calling getHostAddress() method.

What is an InetAddress?

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.

What is the data type of IP address in Java?

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.


1 Answers

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.

like image 105
MrSimpleMind Avatar answered Sep 25 '22 12:09

MrSimpleMind