我正在尝试在不使用序列化的情况下发送 C 中的结构
// client
typedef struct student_rec {
char name[25];
float gpa;
int pid;
} stu;
stu stu = { "Ray T Champion" , 4.0 , 12345666};
sendto(sk,&stu,sizeof(struct student_rec),0,&remote,sizeof(remote));
//server
typedef struct student_rec {
char name[25];
float gpa;
int pid;
} stu;
stu s ;
struct student_rec *ptr;
ptr = &s;
recvfrom(sk,&s,sizeof(struct student_rec),0,&remote,&rlen);
printf("%s\n", ptr->name);
printf( "%d\n", ptr->pid );
我收到的名称很好,但 pid 不正确,我得到垃圾值,我不关心字节序,我只是希望能够一次性发送结构。
最佳答案
您面临字节顺序问题。
您发送12345666
,它与0x00BC6142
相同
您会收到1113701376
,它等于0x4261BC00
。
发送之前转换为网络字节顺序
stu.pid = htonl(stu.pid);
接收后转换(返回)为主机字节顺序。
stu.pid = ntohl(stu.pid);
关于c - 如何使用UDP套接字在C中发送结构而不进行序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28659913/