我在接收来自 python 客户端的请求的 C tcp 套接字服务器中读取字节时遇到了问题。我有以下结构作为我的接收模板
struct ofp_connect {
uint16_t wildcards; /* identifies ports to use below */
uint16_t num_components;
uint8_t pad[4]; /* Align to 64 bits */
uint16_t in_port[0];
uint16_t out_port[0];
struct ofp_tdm_port in_tport[0];
struct ofp_tdm_port out_tport[0];
struct ofp_wave_port in_wport[0];
struct ofp_wave_port out_wport[0];
};
OFP_ASSERT(sizeof(struct ofp_connect) == 8);
我可以正确读取前两个 32 位字段,但我的问题是 pad 字段后面的 in_port[0] 似乎是错误的。当前读取的方式是
uint16_t portwin, portwout, * wportIN;
wportIN = (uint16_t*)&cflow_mod->connect.in_port; //where cflow_mod is the main struct which encompasses connect struct template described above
memcpy(&portwin, wportIN, sizeof(portwin) );
DBG("inport:%d:\n", ntohs(portwin));
不幸的是,这没有给我预期的输入端口号。我可以在wireshark中检查客户端正在发送正确的数据包格式,但我觉得我读取输入/输出端口的方式是错误的。或者是因为python发送数据的方式?你能就我哪里出错以及为什么出错提供一些建议吗?提前致谢。
最佳答案
struct ofp_connect 的声明违反了 ISO C 标准的以下条款:
6.7.2.1 Structure and union specifiers ... 18 As a special case, the last element of a structure with more than one named member may have an incomplete array type; this is called a flexible array member.
请注意,在您的情况下in_port
和out_port
应该被声明为 in_port[]
和out_port[]
要利用上面的子句,在这种情况下,您将拥有两个个灵活的数组成员,这是上面的子句所禁止的。零长度数组声明是许多编译器(例如包括 gcc)采用的约定,它具有相同的语义,但在您的情况下,都是 in_port
和out_port
共享相同的空间(基本上是 ofp_connect
结构后面的任何字节)。此外,为了使其工作,您必须在结构之后为灵活数组成员分配一些空间。因为,正如你所说,struct connect
是更大结构的一部分,访问in_port
返回存储在connect
之后的包含结构的成员中的“值”子struct
关于c - 从 C 中的数据包中读取未初始化的无符号 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18304420/