简体   繁体   中英

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). Sequence number is unsigned long int type. 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. 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. Only the first line should assign to pack.seq_num, 3 others must be adding (with +=).

In the decode function you reassign to the seq_num member for every line except the last eight bits. So that means you will only get the low 16 bits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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