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

Python批量IP地址验证触发TypeError错误的解决方案咨询

报错原因分析

socket.connect()方法仅接受字符串格式的单个IP/域名作为入参,你直接将IP列表传给host参数后,调用s.connect((host, 2440))时相当于把整个列表塞给了需要字符串的位置,就触发了这个类型错误。
你用到的所有库都是Python标准库,不需要额外安装第三方依赖。原代码是通过TCP连接指定端口(默认2440)的方式检测连通性,不是传统的ICMP ping,使用前确认你要检测的IP开放了对应端口即可。

批量IP检测实现方案

修改核心逻辑为遍历IP列表逐个检测,这里默认规则为只要有一个IP连通就判定网络正常,所有IP都不通才判定网络断开,如果需要其他判定规则可以自行调整。
修改后的完整可运行代码如下:

import winsound
import socket
import time
import datetime
import os
import sys

LOG_FNAME = "network.log"
FILE = os.path.join(os.getcwd(), LOG_FNAME)

# 可自行修改要检测的IP列表和对应端口
CHECK_HOSTS = ['127.0.0.1', '114.114.114.114', '223.5.5.5']
CHECK_PORT = 2440  # 按需调整端口,比如检测web服务可以改成80/443

def send_ping_request(timeout=3):
    for host in CHECK_HOSTS:
        try:
            socket.setdefaulttimeout(timeout)
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((host, CHECK_PORT))
            s.close()
            return True  # 只要有一个IP通就返回正常
        except OSError:
            continue
    # 所有IP都不通才返回异常
    return False

def write_permission_check():
    try:
        with open(FILE, "a") as file:
            pass
    except OSError as error:
        print("日志文件创建失败,检查路径权限")
        sys.exit()

def calculate_time(start, stop):
    time_difference = stop - start
    seconds = float(str(time_difference.total_seconds()))
    return str(datetime.timedelta(seconds=seconds)).split(".")[0]

def mon_net_connection(ping_freq=2):
    monitor_start_time = datetime.datetime.now()
    motd = f"网络监控启动于: {str(monitor_start_time).split('.')[0]} 检测间隔: {ping_freq} 秒"
    print(motd)
    with open(FILE, "a") as file:
        file.write("\n")
        file.write(motd + "\n")

if __name__ == '__main__':
    # 先检查日志写入权限
    write_permission_check()
    mon_net_connection()
    ping_freq = 2
    while True:
        if send_ping_request():
            time.sleep(ping_freq)
        else:
            down_time = datetime.datetime.now()
            fail_msg = f"网络断开时间: {str(down_time).split('.')[0]}"
            winsound.Beep(400,400)
            print(fail_msg)
            with open(FILE, "a") as file:
                file.write(fail_msg + "\n")
            i = 0
            while not send_ping_request():
                time.sleep(1)
                i += 1
                if i >= 3600:
                    i = 0
                    now = datetime.datetime.now()
                    continous_message = f"网络持续断开中: {str(now).split('.')[0]}"
                    print(continous_message)
                    with open(FILE, "a") as file:
                        file.write(continous_message + "\n")
            # 网络恢复
            up_time = datetime.datetime.now()
            uptime_message = f"网络恢复时间: {str(up_time).split('.')[0]}"
            down_duration = calculate_time(down_time, up_time)
            _m = f"网络断开时长: {down_duration}"
            print(uptime_message)
            print(_m)
            with open(FILE, "a") as file:
                file.write(uptime_message + "\n")
                file.write(_m + "\n")

调整说明

  • 要检测的IP列表和端口统一放到了CHECK_HOSTS和CHECK_PORT变量里,按需修改即可
  • 修复了原代码的缩进错误、提示信息本地化问题
  • 新增了启动权限检查逻辑,避免运行中写日志报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:27:02