簡體   English   中英

C ++通過UDP套接字發送結構

[英]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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM