Home > Uncategorized > Packet fragmentation over the internet

Packet fragmentation over the internet

Somebody wrote to me telling me that the code I included in my book to send and receive files via TCP sometimes hangs.

  You can improve the handling of files within the TCP file reciever program in two ways.

Firstly, instead of
"if (thisRead==0) break;"
it should be
"if (thisRead<=0) break;"
Furthermore, it is possible for packets of less than 1024 bytes to be sent at a time (this does not
happen over a local network, but sometimes happens over the internet). This could lead to file
corruption where packet-fragments are padded with zero’s in the output file.
So the code could be further improved thus:

System.Collections.ArrayList al = new ArrayList();

byte[] RecvBytes = new byte[Byte.MaxValue];

Int32 bytes;

Int32 totalLength=0



bytes = networkStream.Read(RecvBytes, 0,RecvBytes.Length);

if (bytes<=0) break;

totalLength += bytes;




= al.GetRange(0,totalLength);



[] returnedData = (byte[])al.ToArray((new byte()).GetType());



and also define the function cropByteArray thus:


byte[] cropByteArray(byte[] inputArray, Int32 crop)
byte[] outputArray = new byte[crop];
for (int i=0;i<crop;i++)
return outputArray;

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s