我想通过 C 中的套接字传递结构。我在这里阅读了它:
Passing a structure through Sockets in C
但我的问题是我有一个整数结构数组,我不知道如何序列化和反序列化它,有什么建议吗?
struct packet{
int id;
char buffer[512];
int array[4];
}
序列化函数,它正在工作,但缺少整数数组
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;
}
最佳答案
你可以这样发送:
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
你可以这样接收:
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
和 ntoh
指的是一个函数族。您必须选择适合您的数据类型的函数。 See here.
关于c - 通过C中的套接字传递具有整数数组的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25287551/