简体   繁体   中英

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

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");

You're likely to want to do this:

// Parse IP parts into an int array
int[] ip = new int[4];
String[] parts = "123.45.55.34".split("\\.");

for (int i = 0; i < 4; i++) {
    ip[i] = Integer.parseInt(parts[i]);
}

Or this:

// Add the above IP parts into an int number representing your IP 
// in a 32-bit binary form
long ipNumbers = 0;
for (int i = 0; i < 4; i++) {
    ipNumbers += ip[i] << (24 - (8 * i));
}

Of course, as others have suggested , using InetAddress might be more appropriate than doing things yourself...

You can do it for an IP V4 adress as the parts are just the four bytes of the integer version.

Do this to convert an InetAdress to its integer representation :

int result = 0;  
for (byte b: inetAdress.getAddress())  
{  
    result = result << 8 | (b & 0xFF);  
}

Note that you shouldn't use 32 bits integers for IP addresses now, as we're entering the era of IPV6 addresses.

EDIT : to parse a string like "123.45.55.34" to something useful in java, you may use INetAddress.getByName(yourString)

You need to realize that an IPv4 address in the form 123.45.55.34 is actually 4 three digit numbers representing each byte of the address. Parsing the entire string all at once won't work.

Others have mentioned using an InetAddress , but if all you have is a string representation of the IP you can't easily instantiate an InetAddress as far as I know.

What you can do is something like the following:

public static int parseIp(String address) {
    int result = 0;

    // iterate over each octet
    for(String part : address.split(Pattern.quote("."))) {
        // shift the previously parsed bits over by 1 byte
        result = result << 8;
        // set the low order bits to the current octet
        result |= Integer.parseInt(part);
    }
    return result;
}

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
}
System.out.println(
        ByteBuffer.allocate(Integer.BYTES)
        .put(InetAddress.getByName("0.0.1.0").getAddress())
        .getInt(0));

Output:

256

IPAddressUtil#textToNumericFormatV4 performs better than String#split to get bytes of ip, besides, it checks if the ip is valid

 public int intOfIpV4(String ip) {
        int result = 0;
        byte[] bytes = IPAddressUtil.textToNumericFormatV4(ip);
        if (bytes == null) {
            return result;
        }
        for (byte b : bytes) {
            result = result << 8 | (b & 0xFF);
        }
        return result;
    }

I think you might be misunderstanding your own problem. Are you trying to convert that into a single int value? If you are doing that then the premise of your question is wrong because IP numbers are not one number but multiple byte values. It isn't 123,456,789,000 but rather byte 123 byte 455 byte 789 and byte 000. I know that these are not real byte numbers but the point is is that this is not 123 billion 456 million 789 thousand,000. It seems to me that you are treating the entire thing as a single integer and that isn't the case with IP addresses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM