In Python, what is the best way to determine if an IP address (e.g., '127.0.0.1'
or '10.98.76.6'
) is on a private network? The code does not sound difficult to write. But there may be more edge cases than are immediately apparent, and there's IPv6 support to consider, etc. Is there an existing library that does it?
netaddr is a Python library for representing and manipulating network addresses. IPAddress('input ip'). is_private() will return true if the input ip address private, else it will return false.
You can check an IP address against the ranges for public vs private IP addresses to see if a particular IP address is public or private. All private IP addresses begin with 10, 172, or 192, though some public IP addresses may also begin with 172 and 192.
A public IP address identifies you to the wider internet so that all the information you're searching for can find you. A private IP address is used within a private network to connect securely to other devices within that same network. Each device within the same network has a unique private IP address.
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_private True
If using Python 2.6 or higher I would strongly recommend to use a backport of this module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With