Python Ipware

3.0.0 · active · verified Fri Apr 10

A Python package for server applications to retrieve the client's IP address. It provides a robust and accurate solution for identifying IP addresses, particularly in complex network environments involving proxies and load balancers. The current version is 3.0.0, released on April 19, 2024. The library is actively maintained with a focus on accurate IP retrieval.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate `IpWare` and retrieve the client's IP address from a simulated HTTP request metadata dictionary. It also includes examples of configuring `IpWare` for environments behind trusted proxies using `proxy_count` and `proxy_list` parameters to ensure accurate IP resolution.

from python_ipware import IpWare
from pprint import pprint

# Simulate a request.META or request.environ dictionary from a web framework
# In a real web application, this dictionary would be provided by Django (request.META)
# or Flask (request.environ).
simulated_meta = {
    'REMOTE_ADDR': '192.168.1.100', # Direct connection IP (e.g., last proxy)
    'HTTP_X_FORWARDED_FOR': '203.0.113.45, 198.51.100.10, 192.168.1.100', # Client, Proxy1, Proxy2
    'HTTP_CLIENT_IP': '203.0.113.45',
    'HTTP_X_REAL_IP': '203.0.113.45',
}

# Instantiate IpWare with default configuration
ipw = IpWare()

# Get the client IP and a flag indicating if the route is trusted based on configuration
ip, trusted_route = ipw.get_client_ip(simulated_meta)

if ip:
    print(f"Client IP: {ip}")
    print(f"Is routable (global IP): {ip.is_global}")
    print(f"Is private IP: {ip.is_private}")
    print(f"Trusted route: {trusted_route}")
else:
    print("Unable to determine client IP address.")

print("\n--- Custom Proxy Configuration Examples ---")

# Example with proxy_count: If your server is behind 1 known trusted proxy
# The actual client IP is assumed to be the one before the last proxy.
ipw_with_proxy_count = IpWare(proxy_count=1)
ip_pc, trusted_route_pc = ipw_with_proxy_count.get_client_ip(simulated_meta)

if ip_pc:
    print(f"Client IP (with proxy_count=1): {ip_pc}")
    print(f"Trusted route (with proxy_count=1): {trusted_route_pc}")
else:
    print("Unable to determine client IP with proxy_count=1.")

# Example with proxy_list: If you have specific trusted proxy IPs
# Let's assume '198.51.100.10' is a known trusted proxy.
ipw_with_proxy_list = IpWare(proxy_list=['198.51.100.10'])
ip_pl, trusted_route_pl = ipw_with_proxy_list.get_client_ip(simulated_meta)

if ip_pl:
    print(f"Client IP (with proxy_list=['198.51.100.10']): {ip_pl}")
    print(f"Trusted route (with proxy_list=['198.51.100.10']): {trusted_route_pl}")
else:
    print("Unable to determine client IP with proxy_list.")

view raw JSON →