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?
views:
501answers:
3
+14
A:
Check out the IPy module. If has a function iptype()
that seems to do what you want:
>>> from IPy import IP
>>> ip = IP('127.0.0.0/30')
>>> ip.iptype()
'PRIVATE'
Paolo Bergantino
2009-03-27 18:55:23
+1
A:
If you want to avoid importing a module you can just apply a simple regex:
- ^127.\d{123}.\d{123}.\d{123}$
- ^10.\d{123}.\d{123}.\d{123}$
- ^192.168.\d{123}$
- ^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{123}.[0-9]{123}$
Kurt
2009-03-28 08:33:51
+1
A:
A few days after asking this question, I found out about this Google project, ipaddr-py, which appears to have some of the same functionality with respect to determining if an address is private (is_rfc1918
). Apparently this will be standard in Python 3.1.
Jacob Gabrielson
2009-04-03 07:23:27