Convert an IP address to an int/long in Java
In this tutorial, we'll look at the methods to get a decimal (base 10) number from an IP address. Using decimal IP encoding (base 10) is a bit weird although allowed in the browser.How to encode the IP address in decimal
An IP address is made up of a group of 4 numbers. For example, if you want to encode 192.168.1.1 in decimal, you have to detect in Java the numbers separated by "." of the IP address with the function split and put each one in a box in the table. The IP address is base 256, here is the conversion formula:
192 x 256^3 + 168 x 256^2 + 1 x 256^1 + 1 x 1
3221225472 + 11010048 + 256 + 1 = 3232235777
You can check this by going to the browser
http://3232235777Two ways to express the IP address in a decimal number:
1- IP address in bit shift
We shift n*8 bits to the left, it's a method to make the power in a binary way. Here is an example of an 8-bit offset of the last number of 192.168.1.1:![]() |
Example of calculating (1 x 256^1) in binary |
public class IP_Decimale {Output
public static void main(String[] zero) {
String ip = "192.168.1.1";
//IP address in decimal
long iplong = IPenBase10(ip);
System.out.println(iplong);
}
public static long IPenBase10(String IP address) {
long decimal = 0;
//the numbers are separated by dots
//put each in a box in the array
String[] arrayIP = IP.address.split("\\.");
//from right to left
for (int i = 3; i >= 0; i--) {
//convert to long
long ip = Long.parseLong(arrayIP[3 - i]);
//shift (i*8) bits to the left and sum
long bitshift= ip < < (i*8);
decimal += bitshift;
System.out.println(ip+" < < "+(i*8)+" : "+bitshift);
}
return decimal;
}
}
192 < < 24 : 3221225472
168 < < 16 : 11010048
1 < < 8 : 256
1 < < 0 : 1
result: 3232235777
2- Power IP address of 256
This method consists of calculating the power with the function Math.pow and multiply by the digit of the IP address.public static long IPenBase10puiss(String IP address) {References:
long decimal = 0;
String[] arrayIP = IP.address.split("\\.");
//from right to left
for (int i = 0; i<=3; i++) {
long ip = Long.parseLong(arrayIP[i]);
long puiss= ip * (long) Math.pow(256, 3-i);
decimal += powers;
System.out.println(arrayIP[i] +": "+puiss);
}
return decimal;
}
Network in Java: Manipulating IP Addresses
Assist: How to encode an IP address in decimal?
Wikipedia: Bit shifts
rice University: Java Bit Manipulation Guide
StackOverFlow: IP address conversion to decimal and vice versa