refactor(main): 优化 IP头部构造函数的代码结构和注释
- 增加了 IP 头部各个字段的解释性注释 -调整了代码格式,提高了可读性 - 保留了原始功能,未引入新逻辑
This commit is contained in:
parent
a0d3d8363f
commit
55ab04e18c
17
main.py
17
main.py
@ -62,24 +62,37 @@ def construct_ip_header(src_ip, dest_ip, payload_length, protocol):
|
|||||||
Returns:
|
Returns:
|
||||||
bytes: 构造的IP头部。
|
bytes: 构造的IP头部。
|
||||||
"""
|
"""
|
||||||
|
# IP头部的版本号,IPv4为4
|
||||||
version = 4
|
version = 4
|
||||||
|
# IP头部长度,IPv4头部长度为5个32位字节,即20字节
|
||||||
ihl = 5
|
ihl = 5
|
||||||
|
# 服务类型,表示优先权及吞吐量、延迟等特性
|
||||||
tos = 0
|
tos = 0
|
||||||
|
# 总长度,即IP头部加数据部分的长度
|
||||||
total_length = 20 + payload_length # IP头部20字节 + 数据部分
|
total_length = 20 + payload_length # IP头部20字节 + 数据部分
|
||||||
|
# 标识符,用于唯一标识主机发送的每一份数据包
|
||||||
identification = 54321
|
identification = 54321
|
||||||
|
# 标志位与片偏移,用于指示数据包的分割与重组
|
||||||
flags_offset = 0
|
flags_offset = 0
|
||||||
|
# 生存时间,表示数据包可以经过的路由器数量
|
||||||
ttl = 64
|
ttl = 64
|
||||||
|
# 首部校验和,用于错误检测
|
||||||
header_checksum = 0
|
header_checksum = 0
|
||||||
|
|
||||||
src_ip_bytes = socket.inet_aton(src_ip) # 将源IP转换为二进制格式
|
# 将源IP转换为二进制格式
|
||||||
dest_ip_bytes = socket.inet_aton(dest_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',
|
ip_header = struct.pack('!BBHHHBBH4s4s',
|
||||||
(version << 4) + ihl, tos, total_length,
|
(version << 4) + ihl, tos, total_length,
|
||||||
identification, flags_offset, ttl, protocol,
|
identification, flags_offset, ttl, protocol,
|
||||||
header_checksum, src_ip_bytes, dest_ip_bytes)
|
header_checksum, src_ip_bytes, dest_ip_bytes)
|
||||||
|
|
||||||
|
# 返回构造的IP头部
|
||||||
return ip_header
|
return ip_header
|
||||||
|
|
||||||
|
|
||||||
# 构造 ICMP 报文
|
# 构造 ICMP 报文
|
||||||
def construct_icmp():
|
def construct_icmp():
|
||||||
"""
|
"""
|
||||||
|
Loading…
Reference in New Issue
Block a user