Formula for converting IP address to long

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 = "";
let array = ip.split('.');
let int_array => 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)


Have fun!


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.