An IPv4 can have more representations: as string (a.b.c.d) or numerical (as an unsigned int of 32 bits). (Maybe other, but I will ignore them.)
Is there any built in support in Java (8), simple and easy to use, without network access, to convert between these formats?
I need something like this:
long ip = toNumerical("1.2.3.4"); // returns 0x0000000001020304L
String ipv4 = toIPv4(0x0000000001020304L); // returns "1.2.3.4"
If there is no built in such functions in Java, feel free to suggest other solutions.
Thank you
Heres is a way to Convert IP to Number. I found it a valid way to accomplish the task in Java.
This is also how you would implement it in Scala.
Code snippet provided by QuakeCore will throw "java.net.UnknownHostException: Unable to resolve host" on the part where you want to convert it back to string
but the idea of utilizing InetAddress class is correct. Here is what you want to do:
P.S.: If you will do this for some list of ips, validate them to be sure they don't have subnet masks, for example:
78.83.228.0/8
In this case you will need to flatten them:78.83.228.0/8
=>78.83.228.0 78.83.228.1 78.83.228.2 78.83.228.3 78.83.228.4 78.83.228.5 78.83.228.6 78.83.228.7
The can be done using
InetAddress
as follows.