TCP Checksum Generator
-
Hey all, I'm writing a program that can modify packets in c#. Everything is going fine except my TCP checksum generator where it seems to work for some packets but with a few slight changes it generates the wrong thing. It only seems to be doing this when sending packets to my test box, otherwise it works fine. Could the community please have a look at my code and try and find out what is wrong? i know my programming style Isn't exactly neat although any help would be appreciated. I pass it the whole packet and it sends back a string of the checksum in hex format. Cheers -Glen
private static string GenerateTCPChecksum(byte[] packet) { //Clears the existing checksum packet[0x32] = 0x00; packet[0x33] = 0x00; int sum = 0; //Gets the IP header length string ipHeaderLength = Convert.ToString(packet[0x0e], 16); ipHeaderLength = "" + ipHeaderLength[1]; //Gets the packet size not including the ethernet part int packetSize = Convert.ToInt32(Convert.ToString(packet[0x10], 16).PadLeft(2, '0') + Convert.ToString(packet[0x11], 16).PadLeft(2, '0'), 16); //TCP packet size int length = packetSize - (Int32.Parse(ipHeaderLength) * 4); //TCP packet size //Adds up the whole TCP packet for (int i = 0x22; i < packet.Length; i++) { try { sum = sum + Convert.ToInt32(Convert.ToString(packet, 16).PadLeft(2, '0') + Convert.ToString(packet[i + 1], 16).PadLeft(2, '0'), 16); } catch (IndexOutOfRangeException) { sum = sum + Convert.ToInt32(Convert.ToString(packet, 16).PadLeft(2, '0') + "00", 16); } i++; } //Adds the psudoheader which is the IP addresses, protocol (TCP) and length sum = sum + (Convert.ToInt32(Convert.ToString(packet[0x1a], 16).PadLeft(2, '0') + Convert.ToString(packet[0x1b], 16).PadLeft(2, '0'), 16)) + (Convert.ToInt32(Convert.ToString(packet[0x1c], 16).PadLeft(2, '0') + Convert.ToString(packet[0x1d], 16).PadLeft(2, '0'), 16)) + (Convert.ToInt32(Convert.ToString(packet[0x1e], 16).PadLeft(2, '0') + Convert.ToString(packet[0x1f], 16).PadLeft(2, '0'), 16)) + (Convert.ToInt32(Convert.ToString(packet[0x20], 16).PadLeft(2, '0') + Convert.ToString(packet[0x21], 16).PadLeft(2, '0'), 16)) + 0x06 + length; string s = Convert.ToString(sum, 16); string carry = "00"; //Seperates carry and the rest if (s.Length >= 5) { carry = s.Substring(0, s.Length - 4); s = s.Substring(s.Length - 4, 4); } //Adds the carry to the rest sum = Convert.ToInt32(s, 16); sum = sum + Convert.ToInt32(carry, 16); //Inverts number(one's complement) sum = 0xffff - sum; s = Convert.ToString(sum