我只是在 C 中使用流式套接字,但在读取从服务器应用程序返回的数据包时遇到问题。下面的代码显示了在客户端和服务器端使用的结构。
struct packet
{
uint16_t f1;
uint16_t f2;
uint32_t f3;
uint16_t pf1;
uint32_t pf2;
};
用于发送的服务器端:
char buffer[14];
struct packet myPacket;
myPacket.f1 = 2321;
myPacket.f2 = 4423;
myPacket.f3 = 2134;
myPacket.pf1 = 765;
myPacket.pf2 = 9867;
htonPacket(myPacket, buffer);
将数据打包到缓冲区的函数。
void htonPacket(struct packet h, char buffer[14]) {
uint16_t u16;
uint32_t u32;
u16 = htons(h.f1);
memcpy(buffer+0, &u16, 2);
u16 = htons(h.f2);
memcpy(buffer+2, &u16, 2);
u32 = htonl(h.f3);
memcpy(buffer+4, &u32, 4);
u16 = htons(h.pf1);
memcpy(buffer+8, &u16, 2);
u32 = htonl(h.pf2);
memcpy(buffer+10, &u32, 4);
}
客户端拆包打印:
void ntohPacket(struct packet* h, char buffer[14]) {
uint16_t u16;
uint32_t u32;
memcpy(&u16, buffer+0, 2);
h->f1 = ntohs(u16);
memcpy(&u16, buffer+2, 2);
h->f2 = ntohs(u16);
memcpy(&u32, buffer+4, 4);
h->f3 = ntohl(u32);
memcpy(&u16, buffer+6, 2);
h->pf1 = ntohs(u16);
memcpy(&u32, buffer+8, 4);
h->pf2 = ntohl(u32);
}
打印解压数据:
printf("myPacket.f1: %d\n", myPacket.f1);
printf("myPacket.f2: %d\n", myPacket.f2);
printf("myPacket.f3: %d\n", myPacket.f3);
printf("myPacket.pf1: %d\n", myPacket.pf1);
printf("myPacket.pf2: %d\n", myPacket.pf2);
当我打印这些值时,很明显我在寻址或写入错误的内存位置时遇到了一些问题,但我似乎找不到错误。
myPacket.f1: 2321
myPacket.f2: 4423
myPacket.f3: 2134
myPacket.pf1: 2134
myPacket.pf2: 50135040