我看到了很多与我的问题相关的答案,但在我的情况下我确实无法使用它。
我正在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, <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b2f34361b3834362b3a3575383436" rel="noreferrer noopener nofollow">[email protected]</a>} 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() 或 receive() 返回传递给它们的字节计数以外的值的情况。生产质量的代码将正确处理错误(例如,通过关闭连接),并且还将正确处理 send() 或 recv() 发送/接收仅传输所请求的一些字节的情况(通过调用 send()/稍后再次调用recv() 来处理剩余的未发送/未接收的字节)。
关于c - 通过 TCP 套接字发送 C 结构体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33114611/