简体   繁体   English

通过C中的套接字传递具有整数数组的结构

[英]Passing a structure with array of integers through sockets in C

I want to pass structure over a socket in C. I read about it here: 我想通过C中的套接字传递结构。我在这里了解到它:

Passing a structure through Sockets in C 通过C中的套接字传递结构

but mine problem is that I have inside of a structure array of integers, and I don't know how can I serialize and deserialize it, any advice? 但是我的问题是我有一个整数结构数组,并且我不知道如何序列化和反序列化它,有什么建议吗?

struct packet{
    int id;
    char buffer[512];
    int array[4];
}

Serialize function , it is working but array of integers is missing 序列化功能,可以正常工作,但缺少整数数组

size_t encode_pack(packet pack, char *buf){

    size_t pack_len;
    unsigned char *pt = buf;
    *pt++ = (pack.id  >> 24) & 255 ;
    *pt++ = (pack.id  >> 16)& 255;
    *pt++ = (pack.id >> 8) & 255;
    *pt++ = (pack.id & 255);

    strcpy(pt,pack.buffer);
    pt += strlen(pack.buffer)+1;
    pack_len = sizeof(pack.id) + strlen(pack.buffer); 

    return pack_len;

}

You can send like this: 您可以这样发送:

struct packet p;
int socket;
// Todo: Get socket, initialize/populate p
int temp=hton(p.id);
send(socket,&temp,sizeof(temp),0);
send(socket,p.buffer,sizeof(p.buffer),0);
for (size_t i=0;i<4;++i) {
    temp=hton(p.array[i]);
    send(socket,&temp,sizeof(temp),0);
}
// Todo: Check send calls to make sure they succeed

And you can receive like this: 这样您会收到:

struct packet p;
int socket;
// Todo: Get socket
int temp;
recv(socket,&temp,sizeof(temp),0);
p.id=ntoh(temp);
recv(socket,p.buffer,sizeof(p.buffer),0);
for (size_t i=0;i<4;++i) {
    recv(socket,&temp,sizeof(temp),0);
    p.array[i]=ntoh(temp);
}
// Todo: Check return value of recv calls to make sure data actually received

hton and ntoh refer to a family of functions. htonntoh是指一系列功能。 You must choose the functions appropriate for your datatype. 您必须选择适合您的数据类型的函数。 See here. 看这里。

Because the sizes of the arrays are known at compile time, you can treat it like the structure in the given example. 由于数组的大小在编译时是已知的,因此您可以将其视为给定示例中的结构。

Think of char buffer[512]; 考虑一下char buffer[512]; , for your purposes, as being the same as char buffer0, buffer1, buffer2, ..., buffer511; ,出于您的目的,与char buffer0, buffer1, buffer2, ..., buffer511; .

Also, using sizeof(struct packet) will still work - again, because the array sizes are known at compile time, the compiler can take them into account when computing the total structure size. 同样,使用sizeof(struct packet)仍然可以工作-同样,由于数组大小在编译时是已知的,因此编译器可以在计算总结构大小时将它们考虑在内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM