Protecting my TCP or UDP conenction.

UltraDog
UltraDog used Ask the Experts™
on
Hi!
I have a client and a server which communicate through TCP and UDP.
I'd like to prevent receiving messages from other processes that may try to connect to my ports.
I take the stream of bytes and make an object out of it, but if this is just a random stream - the program will crash.
How can I do it?
thanks :)
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2012
Commented:
I'd just 'packetise' the messages, by prefixing them with a header. E.g. consider  
struct MyMessage {

  BYTE Header[4];
  BYTE Payload[PAYLOAD_SIZE];
};

Open in new window


You'd fill the 'Payload' part with the data you want to send and 'Header' with some unique value that the receiving side also knows. Now, whenever you receive data that is missing that unique header pattern, you'll know that it was sent by some other application, can dismiss the data and maybe terminate the connection.

Author

Commented:
I already have some header bytes, but what if by some coincidence the other process has the same header?
suppose I put in my header the letter 'A' and the length of the message and so does the other process?
jkr
Top Expert 2012

Commented:
Just make your header longer, e.g. as in the example above. It would be *very* coincidential that four bytes match by chance.
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

Top Expert 2009

Commented:
In any case, you need to make your protocol implementation robust enough to handle bad packets.

At minimum use a giant try/catch block to discard message and close the connection. It shouldnt be possible to crash your app with a bad packet.
Top Expert 2009

Commented:
Are you trying to protect against malice, or against an accident ?

Author

Commented:
against accidents :)
Top Expert 2009
Commented:
Then I would simply add a checksum into the message. If the checksum calculated by the receiver doesn't match the one in the message, the receiver can discard the message.
jkr
Top Expert 2012

Commented:
I'd rather combine the two ideas - that is, if the header does not match, you can skip calculating a checksum, but if it does, a matching checksum will make absolutely sure that the packet originated from a trustworthy source.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial