13

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");
9
  • May i know why you required that? Commented Aug 21, 2012 at 15:09
  • Perhaps InetAddress.getByName("123.45.55.34") is more useful than the address as an int value. Commented Aug 21, 2012 at 15:15
  • @PeterLawrey thanks for your reply, I am having problem with parsing the dotted IP numbers in my queries. I have updated my question :) Commented Aug 21, 2012 at 15:30
  • 1
    You can use the hashCode() returned by this expression but its a bit of a hack. Commented Aug 21, 2012 at 15:35
  • 1
    Your latest edit made most of the answers useless. Please consider asking new questions when making major semantic changes through edits Commented Aug 21, 2012 at 15:45

8 Answers 8

21

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)

Sign up to request clarification or add additional context in comments.

4 Comments

salut @ dystroy, Comment this code that you have provided pourra s'appliquer to my question, I have plus de precision to the question. merci monsieur :)
This is a really different question now. I edited my answer but this starts to be a mess...
Using getByName is probably a bad idea if all you're meaning to do is parse an IP address, since if you're given a hostname instead you'll suddenly be doing synchronous network I/O.
" as we're entering the era of IPV6 addresses", funny that 10 years later we still with IPv4.
20

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...

5 Comments

This is also what I thought he wants to know
@KaI: Yes, it's called an educated guess :-)
@LukasEder thanks for your reply, I am having problem with parsing the dotted IP numbers in my queries. I have updated my question :)
@ :) it is the simplest manner I could have started explaining, :)
Of course, you'll want to use long or you're going to overflow the int and get incorrect values for any IP above 127.255.255.255 ;-)
8

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
}

Comments

7

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;
}

3 Comments

Octal? As in 192.168.0.1? ;-)
@LukasEder, wow, I must be losing it. I fixed the answer, thanks for the heads up.
Well, for a short moment, I was worried myself, if some fact had slipped by my memory ;-)
3
System.out.println(
        ByteBuffer.allocate(Integer.BYTES)
        .put(InetAddress.getByName("0.0.1.0").getAddress())
        .getInt(0));

Output:

256

Comments

1

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.

Comments

1

Sorry for reopening an old queston, but to me seems like it's missing a possible valid and performant solution:

static int ipV4ToInt(int a1, int a2, int a3, int a4){
  return (a1 << 24) ^ (a2 << 16) ^ (a3 << 8) ^ a4;
}

then you can add parsing and validation:

class MyAwesomeIPv4Utils {
  private MyAwesomeIPv4Utils(){} // It's a library, sorry OOP addicted...

  static int validateIpPart(int n){
    if (n == (n & 255))
      return n;
    throw new IllegalArgumentException("Invalid IP v4 part: " + n);
  }
  
  static int validateIpPart(String p){
    return validateIpPart(Integer.parseInt(p));
  }
  
  static int internalIpV4ToInt(int a1, int a2, int a3, int a4){
    // let validation outside, just for performance reasons (e.g. inlining and lazy evaluation): it can be made by the caller
    return (a1 << 24) ^ (a2 << 16) ^ (a3 << 8) ^ a4;
  }
  
  // this can be made public as it handles the validation, and can be used to directly create int when you know the addresses at comple time
  public static int ipV4ToInt(int a1, int a2, int a3, int a4){
    return internalIpV4ToInt(
      validateIpPart(a1),
      validateIpPart(a2),
      validateIpPart(a3),
      validateIpPart(a4)
    );
  }
  
  // this can be exposed too, as it handles both validation and parsing
  public static int ipV4ToInt(String ipStr){
    Objects.requireNonNull(ipStr, "null IP Address");
    // If you prefer you can make this Pattern a static variable, to create it just once and shared (Patterns are thread-safe), but be careful with it's instantiation as it can be null at the first invokation of this static method
    final Pattern ipPattern = Pattern.compile("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})");
    final Matcher m = ipPattern.matcher(ipStr);
    if (!m.matches())
      throw new IllegalArgumentException("Invalid IP v4 address: " + ipStr);

    return internalIpV4ToInt(
      validateIpPart(m.group(1)),
      validateIpPart(m.group(2)),
      validateIpPart(m.group(3)),
      validateIpPart(m.group(4))
    );
  }
}

1 Comment

sorry, but your last edit is making code harder to read/understand, not helpful, and probably no real advantage
-2

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;
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.