Using a RegEx to match IP addresses in Python

后端 未结 13 2286
不思量自难忘°
不思量自难忘° 2020-12-01 04:58

I\'m trying to make a test for checking whether a sys.argv input matches the RegEx for an IP address...

As a simple test, I have the following...

imp         


        
相关标签:
13条回答
  • 2020-12-01 05:32

    I came across the same situation, I found the answer with use of socket library helpful but it doesn't provide support for ipv6 addresses. Found a better way for it:

    Unfortunately it Works for python3 only

    import ipaddress
    
    def valid_ip(address):
        try: 
            print ipaddress.ip_address(address)
            return True
        except:
            return False
    
    print valid_ip('10.10.20.30')
    print valid_ip('2001:DB8::1')
    print valid_ip('gibberish')
    
    0 讨论(0)
提交回复
热议问题