Checking for IP addresses

2019-01-26 10: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)?

标签: python ip ipv6
8条回答
对你真心纯属浪费
2楼-- · 2019-01-26 10:36

IPv4 + IPv6 solution relying only on standard library. Returns 4 or 6 or raises ValueError.

try:
    # Python 3.3+
    import ipaddress

    def ip_kind(addr):
        return ipaddress.ip_address(addr).version

except ImportError:
    # Fallback
    import socket

    def ip_kind(addr):
        try:
            socket.inet_aton(addr)
            return 4
        except socket.error: pass
        try:
            socket.inet_pton(socket.AF_INET6, addr)
            return 6
        except socket.error: pass
        raise ValueError(addr)
查看更多
我只想做你的唯一
3楼-- · 2019-01-26 10: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")
查看更多
登录 后发表回答