Conversion from IP string to integer, and backward in Python Conversion from IP string to integer, and backward in Python python python

Conversion from IP string to integer, and backward in Python


#!/usr/bin/env pythonimport socketimport structdef ip2int(addr):    return struct.unpack("!I", socket.inet_aton(addr))[0]def int2ip(addr):    return socket.inet_ntoa(struct.pack("!I", addr))print(int2ip(0xc0a80164)) # 192.168.1.100print(ip2int('10.0.0.1')) # 167772161


Python 3 has ipaddress module which features very simple conversion:

int(ipaddress.IPv4Address("192.168.0.1"))str(ipaddress.IPv4Address(3232235521))


In pure python without use additional module

def IP2Int(ip):    o = map(int, ip.split('.'))    res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]    return resdef 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()# Exampleprint('192.168.0.1 -> %s' % IP2Int('192.168.0.1'))print('3232235521 -> %s' % Int2IP(3232235521))

Result:

192.168.0.1 -> 32322355213232235521 -> 192.168.0.1