vault backup: 2026-05-17 22:27:07

This commit is contained in:
hhs
2026-05-17 22:27:07 +08:00
parent 64e34e6871
commit bbea71f62b
45 changed files with 8983 additions and 0 deletions
@@ -0,0 +1,224 @@
---
tags: [计算机网络, ping, traceroute, ss, telnet, nc, netstat]
create time: 2026-05-18 04:45
---
# 连通性与状态探测工具
## 概述
排查网络问题时,正确的第一步是判断"到底通不通"。本章覆盖从物理连通性到应用端口层的基础探测工具。
## ping —— ICMP Echo Request/Reply
### 基本用法速查
```bash
$ ping -c 4 example.com # 发 4 个包后自动停止
$ ping -i 0.2 example.com # 每 0.2s 发一个(需 root)
$ ping -s 1472 example.com # 载荷 1472 bytes (接近 MTU 1500)
$ ping -t 64 example.com # 指定初始 TTL
$ ping -q example.com # 静默模式,仅显示统计摘要
$ ping -W 2 example.com # 每个包的超时等待 2 秒
```
### 解读输出指标
```
PING example.com (93.184.216.34) 56(84) bytes of data.
64 bytes from 93.184.216.34: icmp_seq=1 ttl=56 time=14.2 ms
64 bytes from 93.184.216.34: icmp_seq=2 ttl=56 time=13.8 ms
--- example.com ping statistics ---
packets transmitted: 2 # 发送包数
packet loss: 0% # 丢包率
rtt min/avg/max/mdev = 13.8/14.0/14.2/0.2 ms # 往返时间统计
```
| 指标 | 含义 | 合格阈值 |
|------|------|---------|
| packet loss | 丢包率 | 0% ~ 0.1%(局域网不应有丢包)|
| rtt avg | 平均 RTT | LAN < 1ms / 同城 < 20ms / 跨省 30-80ms / 跨洋 80-150ms |
| mdev | RTT 标准差 | < 5ms 正常;抖动大说明拥塞或不稳定 |
> [!warning] ping 不通 ≠ 网络故障
>
> 很多服务器禁用了 ICMP Echo Reply(防火墙策略),此时 ping 不通不代表服务不可用。需要结合 `telnet port` 或 `curl` 综合判断。
```bash
# Linux 内置的 ICMP 防御(防 DDoS flood)
$ sysctl net.ipv4.icmp_ratelimit=1000 # 每秒最多处理 1000 个 ICMP 包
$ sysctl net.ipv4.icmp_ratemask=65535 # 允许的 ICMP 类型掩码
$ sysctl net.ipv4.icmp_echo_ignore_all=1 # 完全忽略所有 ping(极端场景)
```
## telnet / nc —— 端口连通测试
### telnet —— 最原始的端口探测
```bash
# 纯测试端口是否开放
$ telnet example.com 80
Trying 93.184.216.34...
Connected to example.com. # ← Connected = 端口开放 ✅
Escape character is '^]'.
# 手动发 HTTP 请求测试
GET / HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Accept: */*
(blank line 回车)
HTTP/1.1 200 OK # ← 收到响应 = 链路完整 ✅
Content-Type: text/html
...
```
### nc (Netcat) —— 更强大的瑞士军刀
```bash
# 仅测试端口连通 (-z = zero-I/O 模式)
$ nc -zv example.com 80
Connection to example.com port 80 [http] succeeded! # ✅ TCP 3次握手成功
$ nc -zv example.com 443
Connection to example.com port 443 [https] succeeded! # ✅
$ nc -zv example.com 8443
nc: connect to example.com port 8443 (tcp): Connection refused # ❌
# 发送数据并等待响应
$ echo "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" | nc -w 2 example.com 80 | head -5
# DNS 反向查询
$ nc -dvl 0.0.0.0 12345 # 监听模式
$ nc -u -z localhost 53 # UDP 端口测试 (DNS 常用)
```
## ss —— 连接状态快照(取代 netstat)
### ss 基础用法
```bash
# 查看所有 TCP 连接(数字格式,不解析域名)
$ ss -tan
State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
ESTAB 0 0 192.168.1.10:45678 93.184.216.34:443 users:(("chrome",pid=1234,fd=42))
SYN-SENT 0 1 192.168.1.10:54321 10.0.0.1:8080 # 正在尝试握手
LISTEN 0 128 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=5678,fd=6))
TIME-WAIT 0 0 192.168.1.10:443 93.184.216.34:52341 # 等待 2MSL
# 查看特定端口的监听
$ ss -tlnp sport = :80
LISTEN 0 128 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=5678,fd=6))
# 查看所有 TIME_WAIT 连接数(高并发服务器常见问题)
$ ss -tan state time-wait | wc -l
1247
# 查看某进程的所有连接
$ ss -tnp | grep nginx | wc -l
# 诊断 CLOSE_WAIT 堆积(⚠️ 代码 Bug!)
$ ss -tan state close-wait
CLOSE-WAIT 0 0 server:8080 client:54321 # ← 对端已关闭,本地未 close()!
```
### ss 状态速查表
| ss 状态 | 含义 | 严重程度 |
|---------|------|---------|
| ESTABLISHED | 正常通信中 | ✅ 正常 |
| LISTEN | 等待接受连接 | ✅ 正常 |
| SYN-SENT | 客户端发出的 SYN 未收到回复 | ⚠️ 检查对端是否存活 |
| SYN-RECV | 收到 SYN 但未完成三次握手 | ⚠️ 可能 SYN Flood |
| TIME-WAIT | 己方主动关闭后等待 2MSL | ⚠️ 可调 tcp_tw_reuse |
| CLOSE-WAIT | 对端关闭但己方未 close() | 🔴 **Bug!** 检查代码 |
| LAST-ACK | 等待最后一个 ACK | ⚠️ 短暂状态,持续则异常 |
| CLOSING | 同时关闭,互等对方 ACK | ⚠️ 罕见 |
```bash
# 按状态过滤
$ ss -tan state established # 仅已建立
$ ss -tan state syn-sent # 仅半连接中
$ ss -tan state closing # 仅 CLOSING
# 按源/目标 IP 过滤
$ ss -tn daddr 10.0.0.0/8 # 只看内网连接
$ ss -tn src :80 # 只看来自 80 端的
```
> [!tip] ss vs netstat
> `ss` 使用 netlink socket 替代 `/proc/net/tcp`,速度更快、信息更全。Linux 5.x+ 系统上 netstat 已被标记为 deprecated。
## traceroute —— 逐跳路径探测
### 三种实现方式
```bash
# UDP 模式(默认)—— 向高端口发 UDP 包递增 TTL
$ traceroute -n example.com
1 192.168.1.1 0.5ms 0.3ms 0.4ms
2 10.0.0.1 10.2ms 9.8ms 10.1ms
12 93.184.216.34 45.1ms 44.8ms 45.0ms
# ICMP 模式(更可靠,不容易被防火墙拦截)
$ traceroute -I example.com
# 现代替代:tracepath(不需要 root,自动 PMTUD)
$ tracepath example.com
1: 192.168.1.1 0ms reached
2: 10.0.0.1 10ms
...
12: 93.184.216.34 45ms Ascent peak pmtu 1452
```
### traceroute 原理
```mermaid
flowchart LR
P1["TTL=1 → 第1跳路由器<br/>回 ICMP Time Exceeded"] -->|"RTT₁"| R1["第1跳: 192.168.1.1"]
P2["TTL=2 → 第2跳路由器<br/>回 ICMP Time Exceeded"] -->|"RTT₂"| R2["第2跳: 10.0.0.1"]
P3["TTL=N → 到达目标<br/>回 ICMP Port Unreachable"] -->|"RTTN"| Rn["目的地: 93.184.216.34"]
style R1 fill:#DDA0DD,color:#000
style R2 fill:#FFD700,color:#000
style Rn fill:#98FB98,color:#000
```
```bash
# 识别路由问题
$ traceroute -n 8.8.8.8
...
5 * * * # ← 这里丢了?→ 路由器禁了 ICMP
6 * * * # ← 可能是运营商之间互联点
7 108.170.xxx.xxx 50ms 48ms 51ms # ← 回到 Google 边缘
# Windows 等价命令
tracert 8.8.8.8
# macOS 等价命令
traceroute 8.8.8.8
```
## 排错黄金思路回顾
```
问题: 无法访问服务
↓
ping 通吗? → 否 → traceroute 定位断在哪一跳
↓ 是
telnet port 通吗? → 否 → 检查防火墙/selinux → ss 看是否监听
↓ 是
curl 正常吗? → 否 → 应用层问题 → 读日志
↓ 是
浏览器缓存/Cookie/Header 问题
```
## 关联笔记
- [[hhs/NETWORK/ICMP与Ping-Traceroute]] — ping/traceroute 的协议底层原理
- [[hhs/NETWORK/TCP三次握手与四次挥手]] — ss 中看到的状态都对应 TCP 状态机中的某个节点
- [[hhs/NETWORK/DNS与DHCP与WebSocket]] — DNS 解析慢会影响 ping/curl 的表现
- [[hhs/NETWORK/抓包HTTPDNS诊断工具]] — 进一步分析可用 tcpdump/curl/dig
@@ -0,0 +1,249 @@
---
tags: [计算机网络, tcpdump, tshark, curl, dig, iptables, Wireshark]
create time: 2026-05-18 04:50
---
# 抓包、HTTP 调试与 DNS 诊断工具
## 概述
在前一章完成了"通不通"的判断之后,本章深入"报文到了没"和"内容对不对"。涵盖 tcpdump 抓包分析、curl HTTP 调试、dig DNS 诊断以及 iptables 规则排查。
## tcpdump —— 命令行抓包神器
### 基础语法与 BPF 过滤器精选
```bash
sudo tcpdump -i eth0 # 抓取 eth0 所有流量
sudo tcpdump -nn # -n: 不解析域名, -n: 不解析端口名
sudo tcpdump -c 100 # 抓 100 个包后停止
sudo tcpdump -w capture.pcap # 写入 pcap 文件(Wireshark 打开)
sudo tcpdump -A 'port 80' # ASCII 模式打印 HTTP 内容
sudo tcpdump -X 'port 80' # HEX + ASCII 双列输出
```
### BPF (Berkeley Packet Filter) 表达式
```bash
# 按 IP 过滤
sudo tcpdump 'host 93.184.216.34' # 只看这个 IP
# 按端口过滤
sudo tcpdump 'port 80' # HTTP
sudo tcpdump 'port 443' # HTTPS
sudo tcpdump 'port range 8000-9000' # 端口范围
# 组合过滤
sudo tcpdump 'src host 10.0.0.1 and dst port 443' # 源 → 目标端口
sudo tcpdump '(src net 192.168.1.0/24) or (dst net 10.0.0.0/8)' # 多网段
# 匹配 TCP 标志位(非常强大!)
sudo tcpdump 'tcp[tcpflags] & (tcp-syn|tcp-ack) != 0' # SYN+ACK
sudo tcpdump 'tcp[tcpflags] & tcp-syn != 0' # SYN 包(新连接)
sudo tcpdump 'tcp[13] & 0x04 != 0' # 同样匹配 SYN
sudo tcpdump 'tcp[13] & 0x10 != 0' # ACK 标志位
sudo tcpdump 'tcp[tcpflags] & tcp-rst != 0' # RST 包(异常断开)
sudo tcpdump 'tcp[tcpflags] & tcp-fin != 0' # FIN 包(正常关闭)
# 排除法
sudo tcpdump 'not host 192.168.1.1 and not port 22' # 排除网关和 SSH
```
### SYN 包实时观察
```bash
# 实时监控新连接建立
sudo tcpdump -nn 'tcp[tcpflags] & tcp-syn != 0'
08:23:45.123456 IP 192.168.1.100:54321 > 10.0.0.1:8080: S 12345678:12345678(...)
08:23:45.123789 IP 10.0.0.1:8080 > 192.168.1.100:54321: S 87654321:87654321(...)
# ↑ 这就是三次握手的前两个包(SYN 和 SYN-ACK)
# 监控 RST(异常断开)
sudo tcpdump -nn 'tcp[tcpflags] & (tcp-rst) != 0'
```
> [!tip] tcpdump → Wireshark 工作流
> ```bash
> # 1. tcpdump 后台抓包
> sudo tcpdump -w /tmp/app.pcap 'host 10.0.0.1 and port 8080' &
> # 2. 复现问题
> # 3. Ctrl+C 停止抓包
> # 4. Wireshark 打开分析
> wireshark /tmp/app.pcap
> # 5. Wireshark 支持深度解码 HTTP/gRPC/TLS 等协议
> ```
## tshark —— CLI 版 Wireshark
```bash
# 实时过滤 HTTP 请求
$ tshark -i eth0 -Y 'http.request'
No. Time Source Destination Protocol Length Info
12 0.123456 10.0.0.1 93.184.xxx HTTP 450 GET /api/users HTTP/1.1
# 导出字段(CSV 风格)
tshark -r capture.pcap -Y 'http' \
-T fields -e ip.src -e http.host -e http.request.uri
# 只追踪 TLS 握手的 ClientHello
tshark -Y 'tls.handshake.type == 1'
# 1 = ClientHello, 11 = ServerHello, 12 = Certificate, etc.
```
## curl —— HTTP 调试利器
### 详细输出与计时分解
```bash
# -v: verbose 模式,看到完整的握手过程和头部交换
curl -v https://example.com
* Trying 93.184.216.34:443...
* Connected to example.com (93.184.216.34) port 443
* ALPN, offering h2
* ALPN, offering http/1.1
* TLSv1.3, TLS handshake, Client hello (1):
* TLSv1.3, TLS handshake, Server hello (2):
* TLSv1.3, Encrypted Extensions (8):
* TLSv1.3, Certificate (11):
* TLSv1.3, TLS handshake, Finished (5):
* TLSv1.3, Encrypted Change Cipher (1):
* ... SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
# -w: custom output 精确测量各阶段耗时 💡
curl -w '\nDNS Resolve: %{time_namelookup}s\nTCP Connect: %{time_connect}s\nTLS Handshake: %{time_appconnect}s\nFirst Byte: %{time_starttransfer}s\nTotal: %{time_total}s\n' \
-o /dev/null -s https://example.com
# 输出示例:
# DNS Resolve: 0.01234s
# TCP Connect: 0.01567s
# TLS Handshake: 0.04567s
# First Byte: 0.15678s
# Total: 0.23456s
```
```
耗时瓶颈分析:
├─ time_namelookup > 0.1s → DNS 慢 → 考虑 DNS 缓存
├─ time_connect - time_namelookup > 0.1s → TCP 连接慢 → 距离远/NAT 问题
├─ time_appconnect - time_connect > 0.2s → TLS 握手慢 → 证书链长/无 session resumption
└─ time_starttransfer - time_appconnect > 0.5s → 服务端处理慢 → 查应用日志
```
### curl 实战用法
```bash
# 自定义 Header 和认证
curl -H 'Authorization: Bearer token' \
-H 'Content-Type: application/json' \
-X POST -d '{"name":"alice"}' \
https://api.example.com/users
# 跟踪重定向(最多 5 层)
curl -L --max-redirs 5 https://short.link
# 查看响应头(快速判断 CDN/缓存状态)
curl -I https://cdn.example.com/style.css
HTTP/2 200
cache-control: public, max-age=86400
age: 1234
x-cache: HIT # ← CDN 命中
cf-cache-status: HIT # ← Cloudflare 标记
content-encoding: br # ← Brotli 压缩
# SSL 证书检查
openssl s_client -connect example.com:443 -servername example.com
# 关注:
# Verify return code: 0 (ok) ✅
# Verify return code: 20 (unable to get local issuer certificate) ❌
# JSON 美化输出
curl https://jsonplaceholder.typicode.com/users/1 | python3 -m json.tool
```
## dig —— DNS 诊断最强工具
### 常用查询模式
```bash
# A 记录简洁输出
$ dig example.com +short
93.184.216.34
# AAAA 记录(IPv6)
$ dig example.com AAAA +short
2606:2800:220:1:248:1893:25c8:1946
# 权威追踪(从根域名开始逐级查询)
$ dig example.com +trace
;; ->>HEADER<<- opcode: QUERY, status: NOERROR
;; QUESTION SECTION: ;example.com. IN A
;; ANSWER SECTION: example.com. 300 IN A 93.184.216.34
# 指定 DNS 服务器对比
$ dig @8.8.8.8 example.com # Google DNS
$ dig @1.1.1.1 example.com # Cloudflare DNS
$ dig @local_dns_server example.com # 本地 DNS(可能被污染)
# TXT 记录(SPF / DKIM 验证邮件配置)
$ dig example.com TXT +short
"v=spf1 include:_spf.google.com ~all"
# MX 记录(邮件服务器)
$ dig example.com MX +short
10 mail.example.com.
20 mail2.example.com.
# SRV 记录(服务发现,gRPC/Kafka 常用)
$ dig _grpc._tcp.service.consul SRV +short
0 100 8080 api.service.consul.
# 查看 CNAME 链全貌
$ dig www.example.com +multiline
```
### dig 高级用法
```bash
# 区域传输(AXFR,通常被禁止)
$ dig @ns1.example.com example.com axfr
# EDNS Client Subnet(CDN 优化用户体验的关键)
$ dig +ecs=203.0.113.0/24 example.com @1.1.1.1
# DNS resolver 把自己的子网发给 authoritative server
# → authoritative server 返回离用户最近的 CDN 节点 IP
# DoH(DNS over HTTPS)检测
$ curl https://dns.google/resolve?name=example.com&type=A
{"Status":0,"Answer":[{"name":"example.com","type":5,"data":"93.184.216.34",...}]}
```
## iptables / nftables 规则排查
```bash
# iptables 规则排查步骤
sudo iptables -L -n -v # 列出 FILTER 表所有规则及计数器
sudo iptables -t nat -L -n -v # 查看 NAT 表(SNAT/DNAT/MASQUERADE)
sudo iptables -t mangle -L -n -v # 查看 MANGLE 表(TOS/TTL 修改)
# 关键排查命令
sudo iptables-save | grep -A 5 INPUT # 只看 INPUT chain 的上下文
sudo iptables -L FORWARD -n -v --line-numbers # 转发规则(容器/代理场景必查)
# 常见规则导致的"假故障"
# ❌ 忘记放行容器的桥接流量
iptables -I FORWARD -i docker0 -j ACCEPT
# ❌ 没有启用 IP forwarding
sysctl net.ipv4.ip_forward=1
# nftables(iptables 的现代替代品)
sudo nft list ruleset # 列出所有 nft 规则
sudo nft add rule inet filter input tcp dport 22 accept
```
## 关联笔记
- [[hhs/NETWORK/连通性与状态探测工具]] — 先看 ping/ss/telnet 再决定要不要抓包
- [[hhs/NETWORK/ICMP与Ping-Traceroute]] — ping/traceroute 协议原理
- [[hhs/NETWORK/DNS与DHCP与WebSocket]] — DNS 递归查询流程补充 dig 实操
- [[hhs/NETWORK/TCP三次握手与四次挥手]] — tcpdump 中观察 SYN/ACK 交互细节