Skip to main content
 首页 » 编程设计

完整和部分 IP 的 python IP 验证 REGex 验证

2025年05月04日9xing901022

我正在尝试验证输入以查看它是否是有效的 IP 地址(可能是部分地址)。

可接受的输入:172、172.112、172.112.113、172.112.113.114

Not Acceptable 输入:1724,172.11113 等等

这是我创建的一个函数来检查它(但是它验证了 Not Acceptable 输入,如 1724,我似乎无法修复它......请帮忙)

def ipcheck(ip): 
    ippattern_str = '(([1-2]?[\d]{1,2}\.?){0,1}(\.[1-2]?[\d]{1,2}){0,1}(\.[1-2]?[\d]{1,2}\.){0,1}(([1-2]?[\d]{1,2}[\D\W]*)' 
    ippattern = re.compile(ippattern_str) 
    # ippattern is now used to call match, passing only the ip string 
    global matchip 
    matchip = ippattern.match(ip) 
    return matchip 
 
 
ip = sys.argv[1] 
ipcheck(ip) 
 
print matchip 

我觉得也许我需要正确使用 anchor ?我尽我所知尝试了一切,我们将不胜感激。

请您参考如下方法:

也许你可以避免使用正则表达式并让 python socket.inet_aton做这个工作:

import socket 
 
try: 
    socket.inet_aton(addr) 
    # correct IP 
except socket.error: 
    # bad IP 

对于 inet_aton,有效的 IP 地址是以下形式:

       a.b.c.d 
       a.b.c 
       a.b 
       a 

In all of the above forms, components of the dotted address can be specified in decimal, octal (with a leading 0), or hexadecimal, with a leading 0X). Addresses in any of these forms are collectively termed IPV4 numbers-and-dots notation. The form that uses exactly four decimal numbers is referred to as IPv4 dotted-decimal notation (or sometimes: IPv4 dotted-quad notation).

source