有没有更好的方法来检查有效IPv4和IPv6的字符串?

时间:2015-11-27 16:14:02

标签: python ipv6 ipv4

我有以下任务:

使用默认模块识别字符串是否具有有效的IPv4或IPv6地址。我在这里找到了一个使用套接字模块的有趣方法:

import socket

ip = '10.1.0.10'
try:
    # test for IPv4
    socket.inet_pton(socket.AF_INET, ip)
except socket.error:
    try:
        # test for IPv6 
        socket.inet_pton(socket.AF_INET6, ip)
    except socket.error:
        print(ip, " is not valid")

在这种情况下尝试尝试似乎很难看,有更好的方法吗? 考虑到我必须检查大约100个IP的事实,是否有一个不同的模块可以更好地完成相同的事情。

1 个答案:

答案 0 :(得分:7)

您可以使用ipaddress模块​​。可以在此处找到文档:https://docs.python.org/3/library/ipaddress.html

示例代码:

>>> ipaddress.ip_address('192.168.0.1')
IPv4Address('192.168.0.1')
>>> ipaddress.ip_address('2001:db8::')
IPv6Address('2001:db8::')
>>> ipaddress.ip_address('323.4.7.8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
    address)
ValueError: '323.4.7.8' does not appear to be an IPv4 or IPv6 address
>>> ipaddress.ip_address('ffff::4543:1f1f::134')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.4/ipaddress.py", line 54, in ip_address
    address)
ValueError: 'ffff::4543:1f1f::134' does not appear to be an IPv4 or IPv6 address