简体   繁体   中英

How to prevent packets from being duplicated or dropped over UDP in C?

I have an assignment where I have to send messages between a client and a server over a reliable and unreliable network using UDP. The client sends a message to the server, the server reads the message, stores it in a local file, then sends the client an acknowledgement in return. Over the reliable network, my code is working smoothly and packets are never dropped, duplicated or reordered.

To set up the unreliable network, my professor had us run sudo tc qdisc add dev lo root netem delay 100ms 20ms 25% loss 0.5% duplicate 1% reorder 25% 50% in our terminal in order to create an emulated unreliable network.

I simply cannot wrap my head around a way to prevent my packets from being duplicated or dropped. I haven't posted any code because I don't want it to seem like I'm asking for answers. I'm trying to understand the methodology behind it as I'm not very experienced in socket or network programming. Is there any way to prevent my packets from being duplicated or dropped over the unreliable network?

In this case you should be using a custom protocol, I can think of this
first we should have a number in our packets that helps us track what is sent and received, lets call it PacketId,
the sender sends a packet with its unique ID, and stores it and starts a timer waiting for ACK, if ACK for that certain ID was received it is removed from queue and we send next packet, if not and timer overflows, that packet is send again,
One last thing about ID is that it should increment by one for each packet.
In the receive side you are only waiting for a specific ID, lets say that at start you are waiting for ID 0, any other packet that is received is ignored until that specific ID is detected, then you increment the expected ID by one and go forward.
There can be a case that ACK lost and server sends back previous packet, so you should ACK those packets too even if they are not expected, and be sure not to process these packets twice.

This is a basic schema that came to my mind, it only send a packet at a time, with a little tweak it can adapt to send multiple pakcets at a time and wait for ACK

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