[英]send struct with pointer char over UDP socket in c linux module
我必須通過udp套接字在兩台計算機之間發送結構,我需要的信息是發送如下結構:
unsigned long x;
unsigned long y;
char *buf;
我必須一次發送該結構。
我的問題是:如何處理這種結構,例如設置一個可以通過套接字發送的變量,尤其是當變量buf的大小不固定時
謝謝您的幫助
您無法發送指針,在進程空間之外沒有任何意義。 相反,您必須對其進行序列化,即復制到陣列並發送。 並且在字符串之前,您還需要存儲其長度。 你可以試試:
char sendbuf[...];
int len = strlen(buf);
memcpy(sendbuf, &x, sizeof(x));
memcpy(sendbuf + sizeof(x), &y, sizeof(y));
memcpy(sendbuf + ..., &len, sizeof(len));
memcpy(sendbuf + ..., buf, len);
您將需要將結構中的所有內容依次復制到單獨的char緩沖區中,然后將其寫入套接字。 可選地,由於結構中的char *緩沖區的長度不是固定的,因此通常最好計算要發送的內容的大小,並在消息的開頭將其寫為整數,以便在另一端您正在發送的數據包的長度可以通過接收套接字進行驗證。
在另一端解壓縮數據時,只需從接收緩沖區的開頭開始,然后將memcpy數據轉換為值
char *消息; //這是指向//收到的消息緩沖區開始的指針
// TODO: assign message to point at start of your received buffer.
unsigned long xx;
unsigned long yy;
memcpy(&xx,message,sizeof(unsigned long)); // copy bytes of message to xx
message += sizeof(unsigned long); // move pointer to where yy SHOULD BE
// within your packet
memcpy(&yy,nessage,sizeof(unsigned long)); // copy bytes to yy
message += sizeof(unsigned long); // message now points to start of
// the string part of your message
int iStringLength = // ?????? You need to calculate length of the string
char tempBuffer[1000]; // create a temp buffer this is just for illustration
// as 1000 may not be large enough - depends on how long
// the string is
memcpy(tempBuffer,message,iStringLength);
然后xx,yy包含您的長值,tempBuffer包含字符串。 如果您希望字符串在當前范圍之外繼續存在,則需要分配一些內存並將其復制到那里。 您可以通過整個消息的大小減去2個未簽名的長項的大小來計算此字符串的大小(或者按照我上面的建議,也可以使用數據包中發送的額外項)。
我希望這可以澄清您需要做什么
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.