c - C 中的写入和读取,套接字 AF_UNIX

标签 c sockets system-calls

我正在用 C 编写一些套接字函数,但遇到了这个问题。 我有一个包含三个字段的结构:

typedef struct {
  char type;           
  unsigned int length; 
  char *buffer;        
} message_t;

我需要包装相同的字符串(类型、长度、缓冲区)并将其自动写入套接字中。之后,使用读取函数,我需要读取消息并将三个字段插入到同一结构中。我不明白如何将 int 转换为固定长度字符串。

最佳答案

这就是想法,虽然我没有测试过,但我使用的是非常相似的。

首先您需要将结构体两侧打包:

#pragma pack(1)
typedef struct {
   char type;
   unsigned int length;
   char *buffer;
} message_t;

要发送数据包,请使用如下函数:

void SendData(char type, unsigned int length, char *data) {
   message_t packet;

   packet.type = type;
   // convert the int to network byte order
   packet.length = htonl(length);

   // Here we have two options to send the packet:
   // 1 with malloc and one send
       packet.buffer = malloc(length);
       memcpy(packet.buffer, data, length);
       length +=sizeof(char);
       length +=sizeof(int);
       // send it in one shut
       send(mySocket, (const char *)&packet, length, 0);
       // release the memory
       free(packet.buffer);

   // 2 without malloc and two sends:
       send(mySocket, (const char *)&packet, sizeof(char)+sizeof(int), 0);
       send(mySocket, data, length, 0);
}

要读取另一侧的数据,请使用如下所示:

BOOL RecvData(message_t *packet) {
   // NOTE: 
   // if packet.buffer is not NULL, the caller of this function must 
   // release the memory allocate here
   packet->buffer = NULL;

   // at the receiver, you need 2 reads:
   // 1 to know how many bytes to read
   // 2 to read those bytes.
   if (recv(mySocket, (char *)packet, sizeof(char)+sizeof(int), 0) > 0)
   {
       // convert the int to host byte order
       packet->length = ntohl(packet->length);
       packet->buffer=malloc(packet->length);
       // if we got the memory, go ahead
       if (packet->buffer != null)
       {
           if (recv(mySocket, packet->buffer, packet->length, 0) == packet->length)
               return TRUE;
       }
   }
   return FALSE;
}

关于c - C 中的写入和读取,套接字 AF_UNIX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16507213/

相关文章:

c - c中链表的子列表?

c - 在 C 中,fgets 和 continue 跳过不止一行

c - gethostbyname() 函数返回空缓冲区

java - 使用一个套接字创建 2 个流

c# - 如何检测套接字断开连接?

xml - 什么是/usr/share/gdb/syscalls 用于

c - 是否有官方文档将读/写函数标记为线程安全函数?

C - 从单亲 fork

c++ - 二进制协议(protocol) - 字节交换技巧

windows - 如何将 uintptr 转换为 go struct