Using the standard Java libraries, what is the quickest way to get from the dotted string representation of an IPV4-address ("127.0.0.1"
) to the equivalent integer representation (2130706433
).
And correspondingly, what is the quickest way to invert said operation - going from the integer 2130706433
to the string representation"127.0.0.1"
?
Using the IPAddress Java library it is simple, one line of code for each direction. Disclaimer: I am the project manager of that library.
Output:
I've modified my original answer. In Sun's implementation of
InetAddress
, thehashCode
method produces the integer representation of the IPv4 address, but as the commenters correctly pointed out, this is not guaranteed by the JavaDoc. Therefore, I decided to use theByteBuffer
class to calculate the value of the IPv4 address instead.The output will be:
Another way:
In case you need to learn the long hand math, you can use Substr to rip out the octets. Mutliply the first octet signifying the Class by (256*256*256) or (2^24) second multiplied by (256*256) (2^16) third multiplied by (256) (2^8) fourth multiplied by 1 or (2^0)
127 * (2^24) + 0 *(2^16) + 0 * (2^8) + 1 * (2^0) 2130706432 + 0 + 0 + 1 = 2130706433
You can also use the Google Guava InetAddress Class
I've not tried it wrt. performance, but the simplest way is probably to use the NIO ByteBuffer.
e.g.
would return you a byte array representing the integer. You may need to modify the byte order.