dsell002
dsell002

Reputation: 1306

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.

Upvotes: 0

Views: 247

Answers (1)

Amardeep AC9MF
Amardeep AC9MF

Reputation: 19024

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.

Upvotes: 3

Related Questions