0

A couple of questions about TCP.

I know that the packet will be "split" or fragmented if it hits a network device with lower MTU etc. But the problems I have is understanding how I "rebuild" my payload in the application. (I've been trying for 2-3 hours now, but can't seem to get it right)

First things first. When sending the packet, what are the pros/cons of the two following options;

NetworkStream ns = client.GetStream();
ns.Write(BitConverter.GetBytes(100));
ns.Write(BitConverter.GetBytes("Test"));

or

NetworkStream ns = client.GetStream();
byte[] payload = BitConverter.GetBytes(100).Concat(BitConverter.GetBytes("Test"));
ns.Write(payload); //, 0, payload.Length);

And how do I rebuild the payload at the recv. part if it has been split? I would love a spoon-feeding on this one as I seem to miss some very important, but not so obvious, part in my current application.

Mike Pennington
  • 41,899
  • 19
  • 136
  • 174
hayer
  • 221
  • 2
  • 8

1 Answers1

5

You don't care at all about MTU or fragmentation. It is the responsibility of the OS's TCP/IP stack to re-assemble a fragmented packet.

You have to remember, it is a TCP "stream", so it doesn't really matter how you read from or write to it; it's just a continual flow of data. It's up to your definition of the packets to provide for data structures passed through that stream.

In many structured protocols, there is a user-defined header and the first field specifies the length of the packet. So you first read X bytes where X is the size of the header. You interpret that header so you know how large the rest of the packet is. Then you read an appropriate number of bytes to get the rest of the packet.

So, of your two examples, it doesn't really matter. Go with whatever is easiest (in this case, the first one.)

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
  • My payload-structure at the moment is; OP code, size, data But if I have understood the chapter on TCP in my book right I might experience that I get OP Code, Size, DataSplit[0] And on the next read I get DataSplit[1], OP Code, Size, Data – hayer Nov 04 '12 at 20:19
  • Sure, but you are over-thinking this. If you follow my directions above, you'll always know exactly how many bytes to read. It doesn't matter at all how the data comes in. Remember, it is a *stream* of data. – Jonathon Reinhart Nov 04 '12 at 20:22