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

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…

Leave a Comment