【问题标题】:validating IP address - python [duplicate]验证IP地址 - python [重复]
【发布时间】:2013-12-06 22:21:33
【问题描述】:

我需要编写一个脚本,打印出一条说明 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(),但我不确定如何处理任何其他非“。”的特殊字符。

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

【问题讨论】:

  • 123.444.333.1从什么时候开始成为有效IP?
  • 期待您的 ipv6 地址正则表达式...为什么不使用库?
  • 2003::5 是一个有效的 IP 地址。

标签: python regex validation split ip-address


【解决方案1】:
>>> 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'

【讨论】:

    【解决方案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 异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-24
      • 2012-02-29
      • 1970-01-01
      • 2012-04-22
      • 2012-11-13
      • 1970-01-01
      • 2018-07-14
      相关资源
      最近更新 更多