After looking at PHP’s ip2long
function I was curious about how this conversion is done. It is quiet simple and to achieve this conversion you have to take the IP address to be in base 256. Then add the product of the base raised to the power of the number position (0, 1, 2 & 3 ) and the value of the number in that position ( 1,0,0 & 127) as illustrated.
Below is a JavaScript code to calculate the long value of an IP.
let ip = "120.8.4.3";
let array = ip.split('.');
let int_array = array.map((num)=> Number(num));
let long_val = int_array[0]*(256**3) + int_array[1]*(256**2)+ int_array[2]*(256**1) + int_array[3]*(256**0)
console.log(long_val);
Have fun!
Leave a Reply