通过UDP套接字的c++发送结构
C++ sending structure via UDP sockets
我试图通过UDP套接字发送结构,我收到DRB_count正确的值,但无法接收KenbStar的值。我做错了什么?我使用同一台机器,在客户端和服务器中使用相同的端口回滚ip 127.0.01。
客户:typedef struct tseTargetCellInformation{
UInt8 DRB_count;
UInt8 *KenbStar;
}tTargetCellConfiguration;
trecTargetCellConfiguration *rx_TargetCellConfiguration_str;
rx_TargetCellConfiguration_str = (trecTargetCellConfiguration*)malloc(sizeof(trecTargetCellConfiguration));
send_TargetCellConfiguration_str->DRB_count=1;
send_TargetCellConfiguration_str->KenbStar = (UInt8*) malloc(1);
send_TargetCellConfiguration_str->KenbStar[0]= 0x5b;
sendto(sd, (char *) (send_TargetCellConfiguration_str), sizeof(tTargetCellConfiguration), 0, (struct sockaddr *)&server, slen)
服务器:typedef struct tseTargetCellInformation{
UInt8 DRB_count;
UInt8 *KenbStar;
}tTargetCellConfiguration;
rx_TargetCellConfiguration_str->KenbStar = (UInt8*) malloc(1);
recvfrom(sd, (char *) (rx_TargetCellConfiguration_str), sizeof(trecTargetCellConfiguration), 0, (struct sockaddr*) &client, &client_length);
因为KenbStar
是一个指针,您必须解引用才能发送它所指向的值,或者接收该值。否则,你只是发送和接收指针(即,不是指向的内容),这通常是没有意义的(特别是如果客户端和服务器是不同的进程)。
换句话说,就像:
sendto(sd, (char *) send_TargetCellConfiguration_str->KenbStar, sizeof(UInt8), ...
和
recvfrom(sd, (char *) rx_TargetCellConfiguration_str->KenbStar, sizeof(UInt8), ...
然而,可能将KenbStar
作为常规成员是最简单的,就像DRB_count
一样,除非您有特定的理由为什么它必须是指针。然后,您可以通过单个调用发送(和接收)整个结构体。
你不能把一个指针从一个内存空间发送到另一个内存空间,并期望它指向同样的东西,尤其是当你没有发送它指向的东西的时候。由于其他十个原因,在网络上发送未编码的结构是不允许的。您需要研究一些表示层,例如XDR。
相关文章:
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 奇怪的结构&GCC&clang(void*返回类型)
- 在 c++ 中拥有一组结构的正确方法是什么?
- vscode g++链路故障:体系结构x86_64的未定义符号
- C++概念:如何使用'concept'检查模板化结构的属性?