Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string (IP numbers) to Integer in Java

Tags:

java

parsing

Example:

// using Integer.parseInt
int i = Integer.parseInt("123");

How would you do the same for?

// using Integer.parseInt
int i = Integer.parseInt("123.45.55.34");
like image 611
Brane Avatar asked Aug 21 '12 15:08

Brane


People also ask

Is IP address integer or string?

The following constitutes a valid IPv4 address: A string in decimal-dot notation, consisting of four decimal integers in the inclusive range 0–255, separated by dots (e.g. 192.168. 0.1 ). Each integer represents an octet (byte) in the address.

Can you convert strings to ints?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.


2 Answers

The IPAddress Java library supports both IPv4 and IPv6 in a polymorphic manner. Disclaimer: I am the project manager of that library.

The following code works with both IPv4 and IPv6 addresses. Using your example IPv4 address:

IPAddress addr = new IPAddressString("123.45.55.34").getAddress();
BigInteger value = addr.getValue(); // 2066560802

If IPv4, you can just go straight to an int value:

if(addr.isIPv4()) {
    int val = addr.toIPv4().intValue(); // 2066560802
}
like image 180
Sean F Avatar answered Sep 21 '22 18:09

Sean F


System.out.println(
        ByteBuffer.allocate(Integer.BYTES)
        .put(InetAddress.getByName("0.0.1.0").getAddress())
        .getInt(0));

Output:

256

like image 40
atoMerz Avatar answered Sep 19 '22 18:09

atoMerz