[英]how to send structure in C using UDP sockets without serialization?
I am trying to send a structure in C without using serialization 我正在尝试使用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 );
I recieve the name just fine , but the pid is not correct, I get garbage values, I am not concerend about endianess, I would just like to be able to send the struct in one shot. 我收到的名称很好,但是pid不正确,我得到了垃圾值,我对持久性不满意,我只想一口气就能发送结构。
You face an endianess issue. 您面临一个麻烦问题。
You send 12345666
which is the same as 0x00BC6142
您发送12345666
与0x00BC6142
相同
and you receive 1113701376
which equal to 0x4261BC00
. 并且您收到1113701376
等于0x4261BC00
。
Before sending convert to network byte order by 在发送之前转换为网络字节顺序
stu.pid = htonl(stu.pid);
After receiving convert (back) to host byte order. 收到转换后(返回)到主机字节顺序。
stu.pid = ntohl(stu.pid);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.