tcpdump 查询源 ip
场景
程序中需要拦截远程服务器的 ip,在配置了远程服务器的公网 ip 地址发现一直不起作用,意识到可能地址被做了转换,所以在本机拦截报文来确认远程服务器的源 ip
方法
需要使用到两个命令:ping,tcpdump,ping 命令从远程机器发出请求,tcpdump 在本机用来捕获 ping 命令发来的 icmp 数据包
远程服务器
- ping 47.xxx.xxx.128
M1Pro ~ % ping 47.xxx.xx.128
PING 47.xxx.xxx.128 (47.xxx.xxx.128): 56 data bytes
64 bytes from 47.xxx.xxx.128: icmp_seq=0 ttl=50 time=40.226 ms
64 bytes from 47.xxx.xxx.128: icmp_seq=1 ttl=50 time=34.793 ms
64 bytes from 47.xxx.xxx.128: icmp_seq=2 ttl=50 time=181.216 ms
本机
- sudo tcpdump -i eth0 icmp
解释: 通过 tcpdump 捕获所有通过 eth0
网卡的 ICMP
数据包。网卡名称根据实际情况替换
15:37:38.211673 IP 222.xxx.35.216 > iZuf69hbg36e6ihbsnua9cZ: ICMP echo request, id 59705, seq 0, length 64
15:37:38.211752 IP iZuf69hbg36e6ihbsnua9cZ > 222.xxx.35.216: ICMP echo reply, id 59705, seq 0, length 64
15:37:39.189403 IP 117.xxx.38.158 > iZuf69hbg36e6ihbsnua9cZ: ICMP echo request, id 31636, seq 0, length 14
15:37:39.189474 IP iZuf69hbg36e6ihbsnua9cZ > 117.xxx.38.158: ICMP echo reply, id 31636, seq 0, length 14
15:37:39.211788 IP 222.xxx.35.216 > iZuf69hbg36e6ihbsnua9cZ: ICMP echo request, id 59705, seq 1, length 64
15:37:39.211812 IP iZuf69hbg36e6ihbsnua9cZ > 222.xxx.35.216: ICMP echo reply, id 59705, seq 1, length 64
从数据包可以看出请求、相应的报文;远程的源ip是222.xxx.35.216
拿一条数据解释例如 15:37:38.211673 IP 222.xxx.35.216 > iZuf69hbg36e6ihbsnua9cZ: ICMP echo request, id 59705, seq 0, length 64
这个数据包是从 IP 地址 222.xxx.35.216
发出的 ICMP
回显请求(ping)到我的服务器(iZuf69hbg36e6ihbsnua9cZ
,服务器主机名)。标识符 59705 和序列号 0 用于跟踪和匹配请求和响应对,数据包的长度为 64 字节。
到这里我们通过 tcpdump 正确获取到了远程的源 ip。