繁体   English   中英

通过c linux模块中的UDP套接字发送带有指针char的结构体

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM