在C中使用UDP发送字符指针
我有一个要发送到 UDP 套接字的结构:
typedef struct
{
char field_id;
short field_length;
char* field;
} field_t, *field_p;
一旦在 UDP 服务器端接收到,我就能够读取 field_id
和 field_length
,但是指向 < code>field 正如预期的那样无效。
正确发送和接收动态 char* 的最佳方法是什么?
我有一个在客户端使用 memcpy
的基本解决方案:
char* data =
(char*)malloc(sizeof(field_t) + (sizeof(char) * strlen(my_field->field)));
memcpy(data, my_field, sizeof(field_t));
memcpy(data+sizeof(field_t), my_field->field, strlen(my_field->field) + 1);
在服务器端:
field_p data = (field_p)buffer;
field_string = (char*)buffer+sizeof(field_t);
是否有更干净的方法来执行此操作,或者这是唯一的方法?
谢谢。
I have a struct that I am sending to a UDP socket:
typedef struct
{
char field_id;
short field_length;
char* field;
} field_t, *field_p;
I am able to read the field_id
and field_length
once received on the UDP server-side, however the pointer to field
is invalid as expected.
What is the best method to properly send and receive a dynamic char*?
I have a basic solution using memcpy
on the client side:
char* data =
(char*)malloc(sizeof(field_t) + (sizeof(char) * strlen(my_field->field)));
memcpy(data, my_field, sizeof(field_t));
memcpy(data+sizeof(field_t), my_field->field, strlen(my_field->field) + 1);
And on the server side:
field_p data = (field_p)buffer;
field_string = (char*)buffer+sizeof(field_t);
Is there a cleaner way of doing this or is this the only way?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当然,您不能通过套接字发送指针 - 删除 char* 字段; 成员。相反,只需将 id 和 size 对与数据本身一起附加即可。使用
writev(2)
或sendmsg(2)
以避免在缓冲区之间移动数据。注意结构成员对齐和填充和数字字节序。
You of course cannot send a pointer over a socket - get rid of the
char* field;
member. Instead, just append id and size pair with the data itself. Usewritev(2)
orsendmsg(2)
to avoid moving data around from buffer to buffer.Watch out for structure member alignment and padding and number endianness.
序列化是你的朋友。
相关链接:
SO-1
SO-2
Serialization is your friend.
Related Links:
SO-1
SO-2
将您的结构定义为:
然后,文本缓冲区将立即跟随您的结构。只需记住一些技巧即可:
不过,我认为这不是标准的。然而,大多数编译器(GCC && MSVC)应该支持这一点。如果您的编译器不支持零大小的数组,您可以使用单元素字符数组 - 只需记住在计算数据包大小时减去额外的一个字节即可。
Define your structure as:
Then, text buffer will immediately follow your structure. Just remember a few tricks:
I don't think it's standard, though. However, most compilers (GCC && MSVC) should support this. If your compiler does not support zero-sized array, you can use one-element char array - just remember to subtract extra one byte when calculating packet size.