如何在创建数据包中使用struck.pack()

0 投票
2 回答
2858 浏览
提问于 2025-04-20 20:37

我在一个用Python创建ICMP ping数据包的程序中遇到了这一行

header = struct.pack("bbHHh", ICMP_ECHO_REQUEST, 0, my_checksum, ID, 1)

这里的"bbHHh"是什么意思呢?

2 个回答

1

请查看这里:

https://docs.python.org/2/library/struct.html#format-characters

这意味着

ICMP_ECHO_REQUEST is a signed char -> integer in python
0 the same
my_checksum is unsigned short -> integer in python
ID the same
h is a short -> integer in python
2

文档在这里:https://docs.python.org/2/library/struct.html - 这是一个格式字符串。你提到的这个例子在C语言中相当于这个:

 struct Foo {
   signed char a;
   signed char b;
   unsigned short c;
   unsigned short d;
   short e;
 }

撰写回答