You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python 3.11中IP地址转int遇ValueError问题求助

问题解决:无法直接将IP字符串转为整数遍历网段

错误原因

你遇到的ValueError是因为带点分的IP字符串(如192.168.250.1)不能直接用int()转换为整数,Python的int()函数只能解析纯数字字符串,无法处理包含.的格式。

解决方案

针对/24网段(前三位固定,最后一位从1到254),最直接的方式是固定前三位IP段,直接遍历最后一位的数值,再拼接成完整IP。

修改后的代码

import wmi
import socket
from datetime import datetime


# 访问Windows WMI对象获取网关和IP地址
wmi_obj = wmi.WMI()
wmi_sql = "select IPAddress,DefaultIPGateway from Win32_NetworkAdapterConfiguration where IPEnabled=TRUE"
wmi_out = wmi_obj.query(wmi_sql)


# 验证IP是否为有效非APIPA地址
def is_valid_ip(ip):
    parts = ip.split(".")
    if len(parts) == 4 and parts[0] == "169" and parts[1] == "254":
        return False
    return True


# 获取网关地址
def get_gateway():
    for dev in wmi_out:
        if dev is not None and hasattr(dev, "DefaultIPGateway"):
            gateway_list = dev.DefaultIPGateway
            if gateway_list and len(gateway_list) > 0:
                non_empty_gateways = [gateway for gateway in gateway_list if gateway]
                if non_empty_gateways:
                    return gateway_list[0]


# 获取网段前三位(比如网关是192.168.250.1,返回"192.168.250")
def get_ip_prefix(gateway):
    return ".".join(gateway.split(".")[:3])


# 扫描指定IP的135端口
def scan(ip):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    socket.setdefaulttimeout(1)
    result = sock.connect_ex((ip, 135))
    sock.close()  # 关闭套接字释放资源
    return result == 0


gateway = get_gateway()
ip_prefix = get_ip_prefix(gateway)

# 遍历/24网段的所有IP(1到254)
for last_octet in range(1, 255):
    current_ip = f"{ip_prefix}.{last_octet}"
    print(f"正在扫描: {current_ip}")
    if scan(current_ip):
        print(f"{current_ip} 的135端口开放")

额外说明

如果需要处理非/24的网段,也可以将IP转换为32位整数进行遍历,再转回IP字符串,示例函数如下:

# IP转32位整数
def ip_to_int(ip):
    parts = list(map(int, ip.split(".")))
    return (parts[0] << 24) | (parts[1] << 16) | (parts[2] << 8) | parts[3]

# 32位整数转IP
def int_to_ip(ip_int):
    return f"{(ip_int >> 24) & 0xFF}.{(ip_int >> 16) & 0xFF}.{(ip_int >> 8) & 0xFF}.{ip_int & 0xFF}"

# 使用示例
start_int = ip_to_int(startingip)
end_int = ip_to_int(endingip)
for ip_int in range(start_int, end_int + 1):
    current_ip = int_to_ip(ip_int)
    print(current_ip)

内容的提问来源于stack exchange,提问作者pandapunk94

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 01:04:52