判断ip 是否正确 python

1 判断ip是否有效

方法一

import socket


def is_valid_ip(ip):

    """Returns true if the given string is a well-formed IP address.

    Supports IPv4 and IPv6.
    """
    ip = ip.strip()
    if not ip or '\x00' in ip:
        # getaddrinfo resolves empty strings to localhost, and truncates
        # on zero bytes.
        return False
    try:
        res = socket.getaddrinfo(ip, 0, socket.AF_UNSPEC,
                                 socket.SOCK_STREAM,
                                 0, socket.AI_NUMERICHOST)
        return bool(res)
    except socket.gaierror as e:
        if e.args[0] == socket.EAI_NONAME:
            return False
        raise
    return True

方法二

import ipaddress
import sys
def valid_ip(ip):
    try:
        #判断 python 版本
        if sys.version_info[0] == 2:
            ipaddress.ip_address(ip.strip().decode("utf-8"))
        elif sys.version_info[0] == 3:
            ipaddress.ip_address(bytes(ip.strip().encode("utf-8")))
        return True
    except Exception as e:
        return False

2 判断ip 是否是内网

import ipaddress
import sys
def private_ip(ip):
    try:
        #判断 python 版本
        if sys.version_info[0] == 2:
            return ipaddress.ip_address(ip.strip().decode("utf-8")).is_private
        elif sys.version_info[0] == 3:
            return ipaddress.ip_address(bytes(ip.strip().encode("utf-8"))).is_private
    except Exception as e:
        return False
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值