Are there any existing libraries to parse a string as an ipv4 or ipv6 address, or at least identify whether a string is an IP address (of either sort)?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Yes, there is
ipaddr
module, that can you help to check if a string is a IPv4/IPv6 address, and to detect its version.But this is not a standard module, so it is not always possible to use it. You also try using the standard
socket
module:For IPv6 addresses you must use
socket.inet_pton(socket.AF_INET6, address)
.I also want to note, that
inet_aton
will try to convert (and really convert it) addresses like10
,127
and so on, which do not look like IP addresses.Try
or get the source code from here
For IPv4, you can use
If it throws an exception,
some_string
is not a valid ip addressFor IPv6, you can use:
Again, it throws an exception, if
some_string
is not a valid address.ipaddr -- Google's IP address manipulation package.
Note that a proposal to include a revised version of the package in the Python standard library has recently been accepted (see PEP 3144).
You can use the
netaddr
library. It has valid_ipv4/valid_ipv6 methods:I prefer ip_interface because it handles situations both with and without prefix mask, for example, both "10.1.1.1/24" as well as simply "10.1.1.1". Needless to say, works for both v4 as well as v6