Checking for IP addresses

后端 未结 8 2041
闹比i
闹比i 2020-12-18 00:03

Are there any existing libraries to parse a string as an ipv4 or ipv6 address, or at least identify whether a string is an IP address (of either sort)?

相关标签:
8条回答
  • 2020-12-18 00:39

    You can use the netaddr library. It has valid_ipv4/valid_ipv6 methods:

    import netaddr
    if netaddr.valid_ipv4(str_ip) is True:
        print("IP is IPv4")
    else:
        if netaddr.valid_ipv6(str_ip) is True:
            print("IP is IPv6")
    
    0 讨论(0)
  • 2020-12-18 00:39

    If you know for sure that the address is valid and only trying to decide whether it is ipv4 or ipv6, wouldn't it be sufficient to do just:

    if ":" in address:
        print("Ipv6")
    else:
        print("Ipv4")
    
    0 讨论(0)
提交回复
热议问题