Regex: How to match IP address in RFC1918 private IPV4 address ranges (in Python)?

后端 未结 3 2001
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-21 03:34

RFC1918 defines private IPv4 addresses as those that fall within any of the following ranges:

10.0.0.0 - 10.255.255.255
172.16.0.0 - 172.31.255.255
192.168.0.0 -         


        
3条回答
  •  鱼传尺愫
    2021-01-21 04:10

    In Python 3.3+ (you did not specify a version, nor why regular expressions are a requirement, so I’ll put this here for completeness), you can:

    import ipaddress
    
    addr_string = # string with your IP address
    try:
        addr = ipaddress.IPv4Address(addr_string)
    except ValueError:
        raise # not an IP address
    if addr.is_private:
        pass # is a private address
    

    See also: ipaddress module documentation

提交回复
热议问题