Search code examples
javaipipv4

Convert IP between IPv4 and numerical format in java


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


Solution

  • The can be done using InetAddress as follows.

    //Converts a String that represents an IP to an int.
    InetAddress i = InetAddress.getByName(IPString);
    int intRepresentation = ByteBuffer.wrap(i.getAddress()).getInt();
    
    //This converts an int representation of ip back to String
    i = InetAddress.getByName(String.valueOf(intRepresentation));
    String ip = i.getHostAddress();