验证IP地址 - python

时间:2013-11-22 06:01:11

标签: python regex validation split ip-address

我需要编写一个脚本,打印出一条声明IP是有效还是无效的声明。

IP地址由四个字节组成(每个字节的有效范围为0-255)。

有效示例:127.0.0.1,123.244.100.1等

无效的例子:124,44,2,2,127.0.2,4,355.23.24.43等。

我猜最简单的方法是使用正则表达式?但是我遇到了一些麻烦。

我还考虑过使用split(),但我不知道如何处理任何其他不是“。”的特殊字符。

任何帮助或建议都会很棒,谢谢

2 个答案:

答案 0 :(得分:3)

>>> import socket
>>> socket.inet_aton("127.0.0.1")    # valid
'\x7f\x00\x00\x01'
>>> socket.inet_aton("127.1")        # oh yes this is valid too!
'\x7f\x00\x00\x01'
>>> socket.inet_aton("127.0.0,1")    # this isn't
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.error: illegal IP address string passed to inet_aton

测试您可以使用的有效IPv6地址

>>> socket.inet_pton(socket.AF_INET6, "2001:db8:1234::")
b' \x01\r\xb8\x124\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'

答案 1 :(得分:2)

您可以使用专门处理IP地址的IPy模块。 https://pypi.python.org/pypi/IPy/

from IPy import IP
try:
    ip = IP('127.0.0.1')
except ValueError:
    # invalid IP

Python 3提供了ipaddress模块​​。 http://docs.python.org/3/library/ipaddress。您可以这样做,而不是使用IPy:

ip = ipaddress.ip_address('127.0.0.1')

这将抛出ValueError异常。

相关问题