Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 716
Jacob Gabrielson Avatar asked Mar 27 '09 18:03

Jacob Gabrielson


People also ask

How do I know if my IP is private or public in Python?

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.

How do you check if an IP is a private IP?

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.

How do you tell the difference between public and private IP?

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.


1 Answers

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.

like image 122
Nik Haldimann Avatar answered Sep 19 '22 11:09

Nik Haldimann