跳到内容
🛠️ToolsShed

Traceroute Reference

完整的traceroute命令参考(Linux、macOS和Windows)。

命令

traceroute <host>

标志

标志说明
-nDo not resolve hostnames (faster)
-m <hops>Set maximum hops (default: 30)
-w <sec>Wait time per probe (default: 5s)
-q <n>Number of probes per hop (default: 3)
-IUse ICMP ECHO instead of UDP
-TUse TCP SYN (requires root)
-p <port>Destination port for UDP/TCP
-i <iface>Use specified network interface
-s <src>Use specified source address
-4 / -6Force IPv4 or IPv6

示例

traceroute google.com

Basic traceroute to a host

traceroute -n 8.8.8.8

Traceroute without DNS resolution

traceroute -m 15 example.com

Limit to 15 hops maximum

traceroute -I google.com

Use ICMP instead of UDP

sudo traceroute -T -p 80 example.com

TCP traceroute on port 80

工作原理

Traceroute 将你的计算机到目标主机的网络路径映射出来。它发送 TTL(生存时间)值逐渐增加的数据包,并记录每个路由器的响应,显示每一跳的 IP 地址和响应时间。这有助于诊断网络连接问题并理解路由路径。

关于此工具

追踪路由(traceroute)是一个诊断工具,用于映射从您的计算机到目标主机的数据包所经过的网络路径,显示每个中间路由器跳和到达每个跳所需的时间。理解数据如何在互联网上传输对于需要诊断连接问题、识别延迟问题或理解路由行为的网络管理员、开发人员和IT专业人员至关重要。此《Traceroute参考指南》为Linux、macOS和Windows系统提供了完整的命令参考,涵盖了每个平台的语法、选项和实际示例。

只需查找您的操作系统的traceroute命令,并探索可用选项的详细说明——无论您需要调整数据包大小、更改最大跳数、设置特定端口号还是配置超时值。无论您是在排查到远程服务器的连接速度缓慢的问题、调查为什么数据包在特定跳被丢弃,还是为基础设施规划记录网络拓扑,此参考都提供实用的指导,不添加不必要的复杂性。

网络专业人士、系统管理员、网络安全专家和云工程师都依赖追踪路由作为其诊断工具包的一部分。对于任何负责维护可靠网络连接、支持生产系统或调查多跳网络环境中问题的人来说,此工具都是必不可少的。

常见问题

代码实现

import subprocess
import platform
import re

def traceroute(host: str, max_hops: int = 30) -> list[dict]:
    """Run traceroute and parse output."""
    system = platform.system()
    if system == "Windows":
        cmd = ["tracert", "-h", str(max_hops), host]
    else:
        cmd = ["traceroute", "-m", str(max_hops), host]

    result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
    lines = result.stdout.splitlines()
    hops = []
    for line in lines[1:]:  # skip header
        # Parse hop number and RTT values
        match = re.match(r"\s*(\d+)\s+(.+)", line)
        if match:
            hop_num = int(match.group(1))
            rest = match.group(2)
            times = re.findall(r"([\d.]+)\s*ms", rest)
            hostname = re.search(r"([\w.-]+)\s+\(", rest)
            hops.append({
                "hop": hop_num,
                "host": hostname.group(1) if hostname else "*",
                "times_ms": [float(t) for t in times],
            })
    return hops

hops = traceroute("google.com", max_hops=15)
for hop in hops:
    avg = sum(hop["times_ms"]) / len(hop["times_ms"]) if hop["times_ms"] else None
    avg_str = f"{avg:.1f} ms" if avg else "*"
    print(f"{hop['hop']:2d}  {hop['host']:<40} {avg_str}")

Comments & Feedback

Comments are powered by Giscus. Sign in with GitHub to leave a comment.