C ++通过UDP套接字发送结构

时间:2013-03-01 11:30:22

标签: c++ sockets udp structure

我正在尝试通过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);

2 个答案:

答案 0 :(得分:2)

因为KenbStar是一个指针,所以您必须dereference才能发送它指向的值,或者接收该值。否则你只是发送和接收指针(即,不是指向的内容),这通常没有任何意义(特别是如果客户端和服务器是不同的进程)。

换句话说,比如:

sendto(sd, (char *) send_TargetCellConfiguration_str->KenbStar, sizeof(UInt8), ...

recvfrom(sd, (char *) rx_TargetCellConfiguration_str->KenbStar, sizeof(UInt8), ...

但是,将KenbStar作为常规成员可能最简单,就像DRB_count一样,除非你有一个特定的理由说明它必须是指针。然后你可以通过一次调用发送(并接收)整个结构。

答案 1 :(得分:0)

您不能将指针发送到一个内存空间到另一个内存空间并期望它指向同一个东西,尤其是当您没有发送它指向的内容时。由于大约十个其他原因,在线上发送未编码的结构也是禁忌。您需要调查一些表示层,例如XDR。