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

标签 c sockets pointers struct network-programming

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

我正在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/

相关文章:

c++ - 拒绝用户运行某些已安装软件的访问权限

c - C中带有Pointer Point的结构的深拷贝

ios - 从 iOS 发送 C++ Protocol Buffer 消息

c++ - 尝试使用对象指针的 boost::multi_array

c - 当 ram 地址存储为 u32 时从 ram 内存中获取值

c - 字符串(命令行)如何存储在 char**argv 和 int *argv 中?

c++ - 我应该停止使用 OpenCV 吗?

c - 多管道实现在 C 中不起作用

Java程序无法连接到我的gmail帐户

javascript - JS Websocket 停留在连接到 TCPListener 的状态 - VB.net