网络宝典
第二套高阶模板 · 更大气的阅读体验

用Python做网络计算:从发包到解析,几行代码就搞定

发布时间:2026-04-10 22:31:21 阅读:1 次

你有没有试过想查一个网站的响应时间,或者批量测几十台服务器的端口通不通?别急着打开各种图形化工具——其实 Python 几行代码就能干完,而且更灵活、更透明。

什么是网络计算?

说白了,就是用程序去完成网络层面的“算术”:比如计算 TCP 连接耗时、统计 ICMP 丢率、解析 DNS 响应结构、抓取 HTTP 头里的 Server 字段……这些都不是玄学,是标准协议+基础 socket 操作,Python 都能原生支持。

最简单的网络计算:测延迟

不用装任何第三方库,Python 自带 sockettime 就能写个简易 ping:

import socket
import time

def ping(host, port=80, timeout=1):
    start = time.time()
    try:
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            s.settimeout(timeout)
            s.connect((host, port))
        return round((time.time() - start) * 1000, 2)
    except Exception:
        return None

print(ping('www.baidu.com'))  # 输出类似:32.45(单位:毫秒)

这段代码不依赖 ping 命令,也不走 ICMP,而是用 TCP 握手模拟“通不通”,适合内网服务健康检查。

再进一步:批量端口扫描

运维同学常要确认一批 IP 的 SSH(22)、HTTP(80)、HTTPS(443)是否开着。写个循环 + 多线程,10 行搞定:

import concurrent.futures
import socket

def check_port(ip, port):
    try:
        socket.create_connection((ip, port), timeout=0.5)
        return f'{ip}:{port} ✅'
    except:
        return f'{ip}:{port} ❌'

ips = ['192.168.1.1', '192.168.1.2']
ports = [22, 80, 443]

with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor:
    tasks = [executor.submit(check_port, ip, p) for ip in ips for p in ports]
    for future in concurrent.futures.as_completed(tasks):
        print(future.result())

跑起来飞快,结果一目了然,比手动 telnet 强太多。

真实场景:DNS 解析耗时分析

用户抱怨“网站打开慢”,真慢在哪儿?先看 DNS 解析花了多久:

import time
import socket

def dns_time(domain):
    start = time.perf_counter()
    try:
        socket.gethostbyname(domain)
        return round((time.perf_counter() - start) * 1000, 2)
    except:
        return None

print(dns_time('github.com'))  # 可能输出:12.78

配合列表推导式,还能一键对比不同 DNS 服务器的效果,比如对比 114.114.114.114 和 8.8.8.8 的解析速度。

小提醒

这些脚本不依赖 Scapy 或 Requests,纯标准库,Python 3.6+ 直接运行;如果需要更底层操作(比如构造自定义 IP 包),再上第三方库也不迟。关键是先理清你要算什么——是延时?通断?协议字段?还是流量特征?目标明确了,Python 就是你的网络计算器。