How would I use python to convert an IP address that comes as a str to a decimal number and vice versa?
For example, for the IP 186.99.109.000 &l
converting an IP string to long integer:
import socket, struct
def ip2long(ip):
"""
Convert an IP string to long
"""
packedIP = socket.inet_aton(ip)
return struct.unpack("!L", packedIP)[0]
the other way around:
>>> socket.inet_ntoa(struct.pack('!L', 2130706433))
'127.0.0.1'
import socket, struct
def ip2long_1(ip):
return struct.unpack("!L", socket.inet_aton(ip))[0]
def ip2long_2(ip):
return long("".join(["{0:08b}".format(int(num)) for num in ip.split('.')]), 2)
def ip2long_3(ip):
return long("".join(["{0:08b}".format(num) for num in map(int, ip.split('.'))]), 2)
ip2long_1 => 0.0527065660363234 ( The Best )
ip2long_2 => 0.577211893924598
ip2long_3 => 0.5552745958088666
def ip2Hex(ip = None):
'''Returns IP in Int format from Octet form'''
#verifyFormat(ip)
digits=ip.split('.')
numericIp=0
count=0
for num in reversed(digits):
print "%d " % int(num)
numericIp += int(num) * 256 **(count)
count +=1
print "Numeric IP:",numericIp
print "Numeric IP Hex:",hex(numericIp)
ip2Hex('192.168.192.14')
ip2Hex('1.1.1.1')
ip2Hex('1.0.0.0')
Here's a summary of all options as of 2017-06. All modules are either part of the standard library or can be installed via pip install.
Module ipaddress (doc) is part of the standard library since v3.3 but it's also available as an external module for python v2.6,v2.7.
>>> import ipaddress
>>> int(ipaddress.ip_address('1.2.3.4'))
16909060
>>> ipaddress.ip_address(16909060).__str__()
'1.2.3.4'
>>> int(ipaddress.ip_address(u'1000:2000:3000:4000:5000:6000:7000:8000'))
21268296984521553528558659310639415296L
>>> ipaddress.ip_address(21268296984521553528558659310639415296L).__str__()
u'1000:2000:3000:4000:5000:6000:7000:8000'
Nothing to import but works only for IPv4 and the code is longer than any other option.
>>> ipstr = '1.2.3.4'
>>> parts = ipstr.split('.')
>>> (int(parts[0]) << 24) + (int(parts[1]) << 16) + \
(int(parts[2]) << 8) + int(parts[3])
16909060
>>> ipint = 16909060
>>> '.'.join([str(ipint >> (i << 3) & 0xFF)
for i in range(4)[::-1]])
'1.2.3.4'
netaddr is an external module but is very stable and available since Python 2.5 (doc)
>>> import netaddr
>>> int(netaddr.IPAddress('1.2.3.4'))
16909060
>>> str(netaddr.IPAddress(16909060))
'1.2.3.4'
>>> int(netaddr.IPAddress(u'1000:2000:3000:4000:5000:6000:7000:8000'))
21268296984521553528558659310639415296L
>>> str(netaddr.IPAddress(21268296984521553528558659310639415296L))
'1000:2000:3000:4000:5000:6000:7000:8000'
Both modules are part of the standard library, the code is short, a bit cryptic and IPv4 only.
>>> import socket, struct
>>> ipstr = '1.2.3.4'
>>> struct.unpack("!L", socket.inet_aton(ipstr))[0]
16909060
>>> ipint=16909060
>>> socket.inet_ntoa(struct.pack('!L', ipint))
'1.2.3.4'
Here's one
def ipv4_to_int(ip):
octets = ip.split('.')
count = 0
for i, octet in enumerate(octets):
count += int(octet) << 8*(len(octets)-(i+1))
return count
One line solution without any module import:
ip2int = lambda ip: reduce(lambda a, b: (a << 8) + b, map(int, ip.split('.')), 0)
int2ip = lambda n: '.'.join([str(n >> (i << 3) & 0xFF) for i in range(0, 4)[::-1]])
Example:
In [3]: ip2int('121.248.220.85')
Out[3]: 2046352469
In [4]: int2ip(2046352469)
Out[4]: '121.248.220.85'