简体   繁体   English

如何在 udp 服务器(在 c 中)和 udp 客户端(python)之间发送和接收 c 结构?

[英]how to send and recv c struct between udp server(in c) and udp client(python)?

I have this structure我有这个结构

struct Data
{
      int id;
      int msglen;
      char msg[100];
}

and I need to pass this struct between udp server and udp client.udp client is python based.我需要在 udp 服务器和 udp 客户端之间传递这个结构。udp 客户端是基于 Z23EEEB4347BDD26BDDFC6B7EE 的。

First, you need to encode the struct data into a single binary buffer首先,您需要将结构数据编码到单个二进制缓冲区中

#include <endian.h>
...
struct Data d { ... };

uint32_t be_id = htobe32(d.id);
uint32_t be_len = htobe32(d.msglen);

size_t pos = 0;
uint8_t buf[sizeof(struct Data)];

memcpy(buf, (const void *)&be_id, sizeof(be_id));
pos += sizeof(be_id);

memcpy(buf + pos, (const void *)&be_len, sizeof(be_len));
pos += sizeof(be_len);

memcpy(buf + pos, (const void *)d.msg, sizeof(d.msg));

Then send the buffer, and parse it from the other side.然后发送缓冲区,并从另一端解析它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM