import socket
import struct
import time
def probe_mtu(target_ip, start_mtu=1480, end_mtu=1580):
for mtu in range(start_mtu, end_mtu):
# 创建UDP套接字
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# 设置UDP数据包的大小
sock.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, mtu)
try:
# 发送一个只有几个字节的数据包
sent_time = time.time()
sock.sendto(b'X' * mtu, (target_ip, 33434))
# 设置超时时间
sock.settimeout(3)
# 尝试接收数据,如果在超时时间内收到ICMP错误回应,则表明MTU值是正确的
try:
sock.recvfrom(1)
except socket.timeout:
print(f"Probe MTU: {mtu} succeeded")
return mtu
except socket.error as e:
# 如果接收到其他错误,则可能是MTU值正确
print(f"Probe MTU: {mtu} failed with error {e}")
return mtu
except socket.error as e:
# 如果发送失败,则可能是MTU值太小
print(f"Probe MTU: {mtu} failed with error {e}")
finally:
sock.close()
# 使用示例
target_ip = "223.5.5.5" # 替换为目标设备的IP地址
mtu_value = probe_mtu(target_ip)
print(f"Estimated MTU of {target_ip} is {mtu_value} bytes.")