diff --git a/main.py b/main.py index 82f7b1f..1d0be1a 100644 --- a/main.py +++ b/main.py @@ -62,24 +62,37 @@ def construct_ip_header(src_ip, dest_ip, payload_length, protocol): Returns: bytes: 构造的IP头部。 """ + # IP头部的版本号,IPv4为4 version = 4 + # IP头部长度,IPv4头部长度为5个32位字节,即20字节 ihl = 5 + # 服务类型,表示优先权及吞吐量、延迟等特性 tos = 0 + # 总长度,即IP头部加数据部分的长度 total_length = 20 + payload_length # IP头部20字节 + 数据部分 + # 标识符,用于唯一标识主机发送的每一份数据包 identification = 54321 + # 标志位与片偏移,用于指示数据包的分割与重组 flags_offset = 0 + # 生存时间,表示数据包可以经过的路由器数量 ttl = 64 + # 首部校验和,用于错误检测 header_checksum = 0 - src_ip_bytes = socket.inet_aton(src_ip) # 将源IP转换为二进制格式 - dest_ip_bytes = socket.inet_aton(dest_ip) # 将目标IP转换为二进制格式 + # 将源IP转换为二进制格式 + src_ip_bytes = socket.inet_aton(src_ip) + # 将目标IP转换为二进制格式 + dest_ip_bytes = socket.inet_aton(dest_ip) + # 打包IP头部信息,转换为二进制格式 ip_header = struct.pack('!BBHHHBBH4s4s', (version << 4) + ihl, tos, total_length, identification, flags_offset, ttl, protocol, header_checksum, src_ip_bytes, dest_ip_bytes) + # 返回构造的IP头部 return ip_header + # 构造 ICMP 报文 def construct_icmp(): """