Human Readable DhcpInfo.ipAddress?

I am wondering how to get a human-accessible IP address from DhcpInfo.ipAddress? The difficulty is that it is an integer, and obviously you cannot store the IP address in integer size. So, how is the IP address encoded so that it can be stored in int? The documentation does not give any help in this problem: http://developer.android.com/reference/android/net/DhcpInfo.html#ipAddress Thanks :-)

+8
android ip dhcp
source share
5 answers

Actually you can.

The IP address is as int: AABBCCDD , and in human-readable form it is AA.BB.CC.DD , but in decimal base. As you can see, you can easily extract them using bitwise operations or by converting an int array to bytes.

See image:

enter image description here

+8
source share

Use this function NetworkUtils.java \ frameworks \ base \ core \ java \ android \ net)

 public static InetAddress intToInetAddress(int hostAddress) { byte[] addressBytes = { (byte)(0xff & hostAddress), (byte)(0xff & (hostAddress >> 8)), (byte)(0xff & (hostAddress >> 16)), (byte)(0xff & (hostAddress >> 24)) }; try { return InetAddress.getByAddress(addressBytes); } catch (UnknownHostException e) { throw new AssertionError(); } } 
+7
source share

obviously you cannot store the IP address in integer

In fact, the entire IP address (v4) is a 32-bit integer (or 128-bit, in the case of IPv6).

The “human-readable” format you are talking about is obtained by dividing the bits of the whole into groups of 8, called “octets,” and converting them to base 10, for example. " 192.168.0.1 ".

The bits of this address will look like this (spaces added for reading):

 11000000 10101000 00000000 00000001 

Which corresponds to the decimal integer 3,232,235,521.

+5
source share

As mentioned by other posters, the IP address is 4 bytes, which can be packed into one int. Andrey gave a good illustration showing how to do this. If you store it in an InetAddress object, you can use ToString () to get a human-accessible version. Something like:

 byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray(); InetAddress address = InetAddress.getByAddress(bytes); String s = address.ToString(); 
+5
source share

just undo the ipaddress you get in bytes

 byte[] bytes = BigInteger.valueOf(ipAddress).toByteArray(); ArrayUtils.reverse(bytes); // then InetAddress myaddr = InetAddress.getByAddress(ipAddress); String ipString = myaddr.getHostAddress(); 
0
source share

All Articles