通过UDP套接字的c++发送结构

C++ sending structure via UDP sockets

本文关键字:结构 c++ UDP 套接字 通过      更新时间:2023-10-16

我试图通过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。