Python3 完全利用内置库判断ip合法性,支持IPv4和IPv6

阅读 1946

完全利用Python3内置库函数判断IP地址合法性,无需安装任何第三方库,同时支持IPv4和IPv6判断,不会误判“1.1.1”为“1.1.0.1”。
Completely use Python3 built-in library functions to judge the legality of IP address. Support both IPv4 and IPv6 address, and will not misjudge “1.1.1” as “1.1.0.1”.

方法一 Method 1

使用“socket”,支持“[fe80::]”格式的IPv6地址。
Use “socket” package and support IPv6 address in “[fe80::]” format.

1
2
3
4
5
6
7
8
9
10
11
12
import socket

def is_valid_ip(ip):
    if not ip or '\x00' in ip:
        return False
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC, socket.SOCK_STREAM, 0, socket.AI_NUMERICHOST)
        return bool(res) and (ip.count('.') == 3 or ':' in ip)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise

示例 Example

1
2
3
4
5
print(is_valid_ip('192.168.0.1'))   #True
print(is_valid_ip('1.1.1'))         #False
print(is_valid_ip('fe80::'))        #True
print(is_valid_ip('[fe80::]'))      #True
print(is_valid_ip('fe80::dc00::1')) #False

参考链接:http://www.coolpython.net/python_senior/pytip/is_valid_ip.html

方法二 Method 2

使用“ipaddress”,不支持“[fe80::]”格式的IPv6地址。更轻量化和高效。
Use “ipaddress” package but not support IPv6 address in “[fe80::]” format. Lighter and more efficient.

1
2
3
4
5
6
7
8
import ipaddress

def is_valid_ip(ip):
    try:
        ipaddress.ip_address(ip)
        return True
    except ValueError:
        return False

示例 Example

1
2
3
4
5
print(is_valid_ip('192.168.0.1'))   #True
print(is_valid_ip('1.1.1'))         #False
print(is_valid_ip('fe80::'))        #True
print(is_valid_ip('[fe80::]'))      #False, different from method 1
print(is_valid_ip('fe80::dc00::1')) #False