How to convert IP address to an integer or a long
Jordan Clist, CTO
Sometimes it is important to convert an IP address eg. 127.0.0.1 to an integer or a long for storage in a database for lookups or for various other reasons. Let this be a definitive guide :)
Eg.
127.0.0.1
Can become
2130706433
PHP
PHP has simple built in library functions to help. Despite them using a 2 instead of “to”.
ip2long('127.0.0.1'); // 2130706433
long2ip(2130706433); // 127.0.0.1
Javascript
Javascript has no built in functions but you can create some simple functions to assist with this.
function ipToLong(dot)
{
var d = dot.split('.');
return ((((((+d[0])*256)+(+d[1]))*256)+(+d[2]))*256)+(+d[3]);
}
function longToIP(int) {
var part1 = int & 255;
var part2 = ((int >> 8) & 255);
var part3 = ((int >> 16) & 255);
var part4 = ((int >> 24) & 255);
return part4 + "." + part3 + "." + part2 + "." + part1;
}
Python
Python has a few options including using the built in socket library. However below is a way to do it without including any external modules.
def IP2Int(ip):
o = map(int, ip.split('.'))
res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
return res
def Int2IP(ipnum):
o1 = int(ipnum / 16777216) % 256
o2 = int(ipnum / 65536) % 256
o3 = int(ipnum / 256) % 256
o4 = int(ipnum) % 256
return '%(o1)s.%(o2)s.%(o3)s.%(o4)s' % locals()