简体   繁体   中英

C Handling multiple types of UDP packets

I'm writing an application which listens for incoming UDP packets. There's a possibility of receiving many different types of packets. For instance, the packets could be defined as such,

Package A: | int a | char b | int c |

Package B: | short int d | int e | char f |

and so forth.

My question is, given that I'm receiving multiple types of messages, what's a good method for coordinating what's being sent with what I'm reading?

As I see it, a "header" could be added to the beginning of each message, defining its type or I could read the message length and compare it to what I have listed, if I know the size of each packet.

Also, if the later is an option, is the packet guaranteed to be the expected length each time?

Edit:

I can also see where just using the packet length could be a problem as there could be multiple messages types of the same length.

Use a header that contains a magic word and a code that defines the type. That way you can assure it was intended for your application, and identifies the correct parser to use.

A sequence number and timestamp could also be useful to detect lost packets and those arriving out of sequence. These are common issues encountered with UDP.

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