定义网络通信的结构

Define structure for network communication in C

本文关键字:结构 网络通信 定义      更新时间:2023-10-16

我想在C中定义一个用于网络传输的结构,例如,我想转移一个动物结构,该结构包含动物名称的可变长度。

afaik,一种方法是 using a predefined length of char array或结构中的 using a buffer,我们可以解析缓冲区(例如,第一个4个字节是动物名称长度,然后是动物名称,然后是其他领域的长度和其他字段其他字段的值),后一种方法的优点是它允许可变名称长度,如以下代码所示:

struct Animal
{
    char   name[128];
    int    age;
}

或:

struct Animal
{
    int    bufferLen;
    char*  pBuffer;
}

我的问题是:我的方法正确吗?即,有一些转移结构的标准方法,并且有更好的方法吗?

我的第二个问题是:我需要注意划桨,即使用#pragma pack(push/pop, n)

预先感谢!

两者都可以正常工作,但是,如果您使用固定的长度包装 sturct,它使其更容易处理,但是您可能会发送比所需的更多数据,例如,假设A 4字节 Integer的代码将发送132字节:

//packed struct
struct Animal {
    char   name[128];
    int    age;
};
Animal a = {"name", 2};
send(fd, &a, sizeof(a), 0);
//and you're done

另一方面,可变长度字段将需要更多的工作来分配内存和包装单个数据包,但是您将能够发送所需的确切字节数,在这种情况下,9字节:

//not necessarily packed   
struct Animal {
    char   *name;
    int    age;
};
//some arbitrary length
int name_length = 50;
//you should check the result of malloc
Animal a = {malloc(name_length), 2}; 
//copy the name
strcpy(a.name, "name");
//need to pack the fields in one buff    
char *buf = malloc(strlen(a.name)+ 1 + sizeof(a.age));
memcpy(buf, a.name, strlen(a.name)+1);
memcpy(buf, &a.age, sizeof(a.age));
send(fd, buf, strlen(a.name)+ 1 + sizeof(a.age));
//now you have to do some cleanup
free(buf);
free(a.name);

编辑:当然,如果您想自己实施该库,则可以使用库为您序列化数据。另外,在Beej的网络编程指南中查看示例序列化代码