Last modified: Apr 27, 2025 By Alexander Williams

Python: Detect Private vs Public IP Address

IP addresses are unique identifiers for devices on a network. They can be public or private. This article explains how to detect them using Python.

What Are Private and Public IP Addresses?

A private IP address is used within a local network. It is not routable on the internet. Examples include 192.168.x.x and 10.x.x.x.

A public IP address is used on the internet. It is globally unique and routable. Your router uses a public IP to communicate online.

Detecting IP Types in Python

Python's ipaddress module makes it easy to check IP types. First, install it if needed.

 
import ipaddress

def check_ip_type(ip):
    try:
        ip_obj = ipaddress.ip_address(ip)
        if ip_obj.is_private:
            return "Private"
        else:
            return "Public"
    except ValueError:
        return "Invalid IP"

Example Usage

Let's test the function with different IP addresses.

 
print(check_ip_type("192.168.1.1"))  # Private
print(check_ip_type("8.8.8.8"))      # Public
print(check_ip_type("10.0.0.1"))     # Private
print(check_ip_type("invalid"))      # Invalid IP


Private
Public
Private
Invalid IP

Understanding IP Ranges

Private IPs fall in specific ranges. These include:

  • 10.0.0.0 to 10.255.255.255
  • 172.16.0.0 to 172.31.255.255
  • 192.168.0.0 to 192.168.255.255

The ipaddress module handles these checks automatically. No need to manually verify ranges.

Handling IPv6 Addresses

The same function works for IPv6. Private IPv6 addresses start with 'fd00::'.

 
print(check_ip_type("fd00::1"))      # Private
print(check_ip_type("2001:db8::1"))  # Public


Private
Public

Practical Applications

Detecting IP types is useful for network security. For example, you can block private IPs from public APIs.

Combine this with other tools like Python AsyncIO for handling multiple connections.

You can also use it with hostname lookups to identify devices.

Common Errors

Ensure the IP string is valid. Invalid formats raise a ValueError.

For more on validation, see this guide.

Conclusion

Python's ipaddress module simplifies IP type detection. It supports both IPv4 and IPv6. Use it to enhance network applications.

For more networking tips, explore our local network IP guide.