<p>您可以使用<strong><a href="https://github.com/un33k/django-ipware" rel="noreferrer">django-ipware</a></strong>,它支持Python<strong>2</strong>&;<strong>3</strong>并处理<strong>IPv4</strong>&;<strong>IPv6</strong>。</p>
<p><strong>安装:</strong></p>
<blockquote>
<blockquote>
<p>pip install django-ipware</p>
</blockquote>
</blockquote>
<p><strong>简单用法:</strong></p>
<blockquote>
<blockquote>
<p>To get client's IP address.</p>
</blockquote>
</blockquote>
<pre><code># In a view or a middleware where the `request` object is available
from ipware import get_client_ip
ip, is_routable = get_client_ip(request)
if ip is None:
# Unable to get the client's IP address
else:
# We got the client's IP address
if is_routable:
# The client's IP address is publicly routable on the Internet
else:
# The client's IP address is private
# Order of precedence is (Public, Private, Loopback, None)
</code></pre>
<p><strong>高级用法:</strong></p>
<blockquote>
<blockquote>
<p>Custom Header - Custom request header for ipware to look at</p>
</blockquote>
</blockquote>
<pre><code>i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR'])
i, r = get_client_ip(request, request_header_order=['X_FORWARDED_FOR', 'REMOTE_ADDR'])
</code></pre>
<blockquote>
<blockquote>
<p>Proxy Count - Django server is behind a fixed number of proxies</p>
</blockquote>
</blockquote>
<pre><code>i, r = get_client_ip(request, proxy_count=1)
</code></pre>
<blockquote>
<blockquote>
<p>Trusted Proxies - Django server is behind one or more known & trusted proxies</p>
</blockquote>
</blockquote>
<pre><code>i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2'))
# For multiple proxies, simply add them to the list
i, r = get_client_ip(request, proxy_trusted_ips=('177.2.2.2', '177.3.3.3'))
# For proxies with fixed sub-domain and dynamic IP addresses, use partial pattern
i, r = get_client_ip(request, proxy_trusted_ips=('177.2.', '177.3.'))
</code></pre>
<p><strong>注意:</strong>阅读此<a href="https://github.com/un33k/django-ipware#notice" rel="noreferrer">notice</a>。</p>