Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert IP between IPv4 and numerical format in java

Tags:

java

ip

ipv4

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

like image 460
Costin Avatar asked Apr 25 '16 09:04

Costin


People also ask

What is the format of IP address in Java?

The IP address is a string in the form “A.B.C.D”, where the value of A, B, C, and D may range from 0 to 255. Leading zeros are allowed. The length of A, B, C, or D can't be greater than 3.

How do I convert numeric to int in Java?

Number. intValue() method returns the value of the specified number as an int.

How do you check IP address is IPv4 or IPv6 Java?

We can use InetAddressValidator class that provides the following validation methods to validate an IPv4 or IPv6 address. isValid(inetAddress) : Returns true if the specified string is a valid IPv4 or IPv6 address. isValidInet4Address(inet4Address) : Returns true if the specified string is a valid IPv4 address.


2 Answers

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();
like image 52
QuakeCore Avatar answered Oct 01 '22 13:10

QuakeCore


Heres is a way to Convert IP to Number. I found it a valid way to accomplish the task in Java.

public long ipToLong(String ipAddress) {

    String[] ipAddressInArray = ipAddress.split("\\.");

    long result = 0;
    for (int i = 0; i < ipAddressInArray.length; i++) {

        int power = 3 - i;
        int ip = Integer.parseInt(ipAddressInArray[i]);
        result += ip * Math.pow(256, power);

    }

    return result;
  }

This is also how you would implement it in Scala.

  def convertIPToLong(ipAddress: String): Long = {

    val ipAddressInArray = ipAddress.split("\\.")
    var result = 0L

    for (i  <- 0  to ipAddressInArray.length-1) {
      val power = 3 - i
      val ip = ipAddressInArray(i).toInt
      val longIP = (ip * Math.pow(256, power)).toLong
      result = result +longIP
    }
    result
  }
like image 40
SparkleGoat Avatar answered Oct 01 '22 14:10

SparkleGoat