简体   繁体   English

通过udp套接字发送C的结构

[英]C sending structure over udp socket

I have implemented udp server and client in C. Server (64-bit PC) is sending udp packets which contain sequence numbers of the packets to the client (also 64-bit PC). 我已经在C中实现了udp服务器和客户端。服务器(64位PC)向客户端(也是64位PC)发送包含数据包序列号的udp数据包。 Sequence number is unsigned long int type. 序列号是unsigned long int类型。 Server correctly reads this sequence number and sends the packet over the socket. 服务器正确读取此序列号,并通过套接字发送数据包。 The problem is at the client side,it reads correctly all packets until he reaches 65 535 packet, then he starts from 0. It makes no sense because also at the client side sequence number of the packetis unsigned long int type. 问题出在客户端,它正确读取了所有数据包,直到到达65 535数据包,然后从0开始。这没有任何意义,因为在数据包的客户端序列号也是unsigned long int类型。 Below are also my function for encoding at the server side at decoding at the client side, maybe you can see mistake? 下面也是我在服务器端进行编码,在客户端进行解码的函数,也许您会看到错误? Thx 谢谢

server encoding 服务器编码

size_t encode(packet pack, char buf[MAX_SIZE]){


    size_t pack_len;
    unsigned char *pt = buf;

    *pt++ = (pack.tos >> 8) & 255;
    *pt++ = (pack.tos & 255);

    *pt++ = (pack.seq_num  >> 24) & 255 ;
    *pt++ = (pack.seq_num  >> 16)& 255;
    *pt++ = (pack.seq_num >> 8) & 255;
    *pt++ = (pack.seq_num & 255);

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

    return pack_len;

}

client decoding 客户解码

packet decode(char *buf) {

    packet pack;
    unsigned char *pt = buf;

    pack.tos = *pt++ << 8;
    pack.tos += *pt++;

    pack.seq_num = *pt++ << 24;
    pack.seq_num = *pt++ << 16;
    pack.seq_num = *pt++ << 8;
    pack.seq_num += *pt++;

    strcpy(pack.buffer, pt);
    return pack;
}

Look at your client-side decoding function: it does "pack.seq_num =" 3 times, then pack.seq_num +=, so effectively you only use last 2 bytes, that's why it overflows every 65535 packets. 查看您的客户端解码功能:它执行“ pack.seq_num =“ 3次,然后执行pack.seq_num + =,因此实际上您只使用最后2个字节,这就是为什么它每65535个数据包都会溢出。 Only the first line should assign to pack.seq_num, 3 others must be adding (with +=). 仅第一行应分配给pack.seq_num,其他三行必须添加(带有+ =)。

In the decode function you reassign to the seq_num member for every line except the last eight bits. decode功能中,您seq_num除最后八位之外的每一行重新分配seq_num成员。 So that means you will only get the low 16 bits. 因此,这意味着您只会得到低16位。

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

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