[英]How can I possibly send this struct over network?
我有以下結構:
struct fetch_info_t {
u_int8_t grocery_type;
u_int8_t arg[1024];
} __attribute__((packed));
我想通過套接字將其發送到服務器,以請求數據。 我非常想避免使用任何庫,例如protobuf
。 grocery_type
可以是1種255的一些雜貨類型之間的任何值,比方說是類型128
,必須提供附加信息。 我不足以提供類型128
,我還想提供Cheeses
作為字符串。 話雖如此,與128
不同,類型129
必須提供一個數字u_int32_t
而不是字符串。
基本上我已經為系統可能需要的附加信息分配了 1024 個字節。 問題是,如何通過套接字發送它,或者更具體地說,使用非系統相關的正確信息填充arg
? 我知道可以使用數字上的htonl
,但我如何實際將緩沖區值設置為該值?
我想象發送的信息實際上最終會將結構指針轉換為 unsigned char 數組,並通過套接字發送它。 請讓我知道是否有更好的方法。
您不能直接將 32 位值分配給數組,因為不能保證正確對齊。
memcpy()
只會復制沒有對齊問題的字節。
u_int32_t the_value=htonl( ... );
struct fetch_info_t the_info;
the_info.grocery_type=129;
memcpy(the_info.arg, &the_value, sizeof(the_value));
然后,因為你的結構是打包的,你可以用
send(my_socket, &the_info,
sizeof(the_info.grocery_type)+sizeof(the_value), 0);
如果您需要發送字符串
char *the_text= ... ;
size_t the_size=strlen(the_text)+1;
struct fetch_info_t the_info;
the_info.grocery_type=128;
memcpy(the_info.arg, the_text, the_size);
send(my_socket, &the_info,
sizeof(the_info.grocery_type)+the_size, 0);
注意這里傳輸'\\0'
是'\\0'
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.