简体   繁体   中英

How do I configure a retransmit timeout in a C UDP socket program?

I have a simple UDP socket program in C. The client transmits data to the server and receives acknowledgements. I already know how to configure a timeout so that if 'recvfrom()' doesn't receive anything in a certain period of time the alarm goes off.

HOWEVER, there are a few more situations I need to handle. What if I receive a reply from an unexpected address, or the reply is not formatted correctly? I don't want to retransmit immediately, only when the alarm goes off.

Let me know if I need to clarify.

Look into select(2) and poll(2) - you can wait on a socket for a specified amount of time. You can then restart the wait with lesser timeout if you need.

If you are on linux, look into epoll(7) and timerfd_create(2) .

You are going to have to do processing on the received datagrams if you want to check and see if they are from an unexpected address or if they are formatted incorrectly. To make handing these cases easier you should build a state machine that handles your different cases.

For example you could have the following states:

  • read timeout
  • data format error
  • invalid transmit address
  • valid data

Also if you detect one of these other error conditions and you don't want to immediately retransmit you will need you some sort of timer or sleep condition to wait until you are ready to retransmit.

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