gpt4 book ai didi

c - 通过 TCP 套接字发送 C 结构

转载 作者:太空宇宙 更新时间:2023-11-04 03:35:27 25 4
gpt4 key购买 nike

我看到了很多与我的问题相关的答案,但我的情况确实无法使用。

我正在 Linux 域下使用 C 语言的套接字编程构建网络模块。我必须实现一个函数,该函数可以发送一个由 int、char、char * 和一些其他结构(嵌套结构)组成的结构。

struct EnQuery
{
char type[6]; // insert, select , update , delete
char * columns; //note here, it's an array of big, {name, age, sex, position, email} not in string
struct Values * values; //an array of values(another struct), {tom, 23, male, student, tom@compan.com} is represented by the second struct values, not in string
struct condition * enCondition; // array of condition, "name=tom and age>30" is represnted by the third struct condition
short len;
short rn;
};

struct Values
{
char * doc;
char key[2];
char s;
};

struct condition
{
short k;
struct condition * children;
};

以上是我要发送的结构。我正在声明变量并使用 send() 函数通过套接字发送。

我将如何通过套接字发送 char *?或者有没有一种方法可以方便地调整 char 数组的长度?

P.S 我不能使用外部库

最佳答案

How would I have to send char * through the socket?

显然,发送指针值不是一件有用的事情,因为指针不会指向接收计算机上的任何有效内容。

因此,您必须发送它指向的数据,而不是发送指针。这样做的典型方法是首先发送指针指向的字节数:

uint32_t sLen = strlen(doc)+1;  // +1 because I want to send the NUL byte also
uint32_t bigEndianSLen = htonl(sLen);
if (send(sock, &bigEndianSLen, sizeof(bigEndianSLen), 0) != sizeof(bigEndianSLen)) perror("send(1)");

....然后发送字符串的字节:

if (send(sock, doc, sLen, 0) != sLen) perror("send(2)");

在接收端,你会做相反的事情:首先接收字符串的长度:

uint32_t bigEndianSLen;
if (recv(sock, &bigEndianSLen, sizeof(bigEndianSLen), 0) != sizeof(bigEndianSLen)) perror("recv(1)");
uint32_t sLen = ntohl(bigEndianSLen);

...然后接收字符串的数据:

char * doc = malloc(sLen+1);
if (recv(sock, doc, sLen, 0) != sLen) perror("recv(2)");
doc[sLen] = '\0'; // paranoia: make sure the string is terminated no matter what

请注意,此示例代码有点幼稚,因为它无法正确处理 send() 或 recv() 返回的值不是传递给它们的字节数的情况。生产质量代码将正确处理错误(例如通过关闭连接),并且还将正确处理 send() 或 recv() 发送/接收仅传输请求的一些字节的情况(通过调用 send()/recv() 稍后再次用于剩余的未发送/未接收字节)。

关于c - 通过 TCP 套接字发送 C 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33114611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com