How do you determine if an IP address is private, in Python? How do you determine if an IP address is private, in Python? python python

How do you determine if an IP address is private, in Python?


Since Python 3.3 there is an ipaddress module in the stdlib that you can use.

>>> import ipaddress>>> ipaddress.ip_address('192.168.0.1').is_privateTrue

If using Python 2.6 or higher I would strongly recommend to use a backport of this module.


Check out the IPy module. If has a function iptype() that seems to do what you want:

>>> from IPy import IP>>> ip = IP('127.0.0.0/30')>>> ip.iptype()'PRIVATE'


You can check that yourself usinghttps://www.rfc-editor.org/rfc/rfc1918 and https://www.rfc-editor.org/rfc/rfc3330. If you have 127.0.0.1 you just need to & it with the mask (lets say 255.0.0.0) and see if the value matches any of the private network's network address. So using inet_pton you can do: 127.0.0.1 & 255.0.0.0 = 127.0.0.0

Here is the code that illustrates that:

from struct import unpackfrom socket import AF_INET, inet_ptondef lookup(ip):    f = unpack('!I',inet_pton(AF_INET,ip))[0]    private = (        [ 2130706432, 4278190080 ], # 127.0.0.0,   255.0.0.0   https://www.rfc-editor.org/rfc/rfc3330        [ 3232235520, 4294901760 ], # 192.168.0.0, 255.255.0.0 https://www.rfc-editor.org/rfc/rfc1918        [ 2886729728, 4293918720 ], # 172.16.0.0,  255.240.0.0 https://www.rfc-editor.org/rfc/rfc1918        [ 167772160,  4278190080 ], # 10.0.0.0,    255.0.0.0   https://www.rfc-editor.org/rfc/rfc1918    )     for net in private:        if (f & net[1]) == net[0]:            return True    return False# exampleprint(lookup("127.0.0.1"))print(lookup("192.168.10.1"))print(lookup("10.10.10.10"))print(lookup("172.17.255.255"))# outputs True True True True

another implementation is to compute the int values of all private blocks:

from struct import unpackfrom socket import AF_INET, inet_ptonlookup = "127.0.0.1"f = unpack('!I',inet_pton(AF_INET,lookup))[0]private = (["127.0.0.0","255.0.0.0"],["192.168.0.0","255.255.0.0"],["172.16.0.0","255.240.0.0"],["10.0.0.0","255.0.0.0"])for net in private:    mask = unpack('!I',inet_aton(net[1]))[0]    p = unpack('!I',inet_aton(net[0]))[0]    if (f & mask) == p:        print lookup + " is private"