Код: Выделить всё
public ushort ComputeChecksum(byte[] ipv4Header, byte[] tcpHeader, byte[] payload)
{
int pseudoHeaderLength = 12; // Pseudo-header is 12 bytes
int totalLength = pseudoHeaderLength + tcpHeader.Length + payload.Length;
byte[] pseudoHeaderAndTcpSegment = new byte[totalLength];
// Copy Source IP address (4 bytes)
Array.Copy(ipv4Header, 12, pseudoHeaderAndTcpSegment, 0, 4);
Console.WriteLine("Claculate TCP CheckSum length:" + totalLength);
Console.WriteLine((BitConverter.ToString(pseudoHeaderAndTcpSegment).Replace("-", " ") + ", "));
Console.WriteLine("");
// Copy Destination IP address (4 bytes)
Array.Copy(ipv4Header, 16, pseudoHeaderAndTcpSegment, 4, 4);
Console.WriteLine((BitConverter.ToString(pseudoHeaderAndTcpSegment).Replace("-", " ") + ", "));
Console.WriteLine("");
// TCP length (2 bytes)
int tcpLength = tcpHeader.Length + payload.Length;
pseudoHeaderAndTcpSegment[8] = (byte)((tcpLength >> 8) & 0xFF);
pseudoHeaderAndTcpSegment[9] = (byte)(tcpLength & 0xFF);
Console.WriteLine((BitConverter.ToString(pseudoHeaderAndTcpSegment).Replace("-", " ") + ", "));
Console.WriteLine("");
// Protocol (1 byte)
pseudoHeaderAndTcpSegment[10] = ipv4Header[9];
Console.WriteLine((BitConverter.ToString(pseudoHeaderAndTcpSegment).Replace("-", " ") + ", ") + " Protocol:" + ipv4Header[9]); // ipv4Header[9] prints 6 like it should
Console.WriteLine("");
// Zero byte (1 byte)
pseudoHeaderAndTcpSegment[11] = 0;
Console.WriteLine((BitConverter.ToString(pseudoHeaderAndTcpSegment).Replace("-", " ") + ", "));
Console.WriteLine("");
// Copy TCP header
Array.Copy(tcpHeader, 0, pseudoHeaderAndTcpSegment, 12, tcpHeader.Length);
// Copy payload
Array.Copy(payload, 0, pseudoHeaderAndTcpSegment, 12 + tcpHeader.Length, payload.Length);
Console.WriteLine((BitConverter.ToString(pseudoHeaderAndTcpSegment).Replace("-", " ") + ", "));
Console.WriteLine("");
return ComputeChecksum(pseudoHeaderAndTcpSegment);
}
private static ushort ComputeChecksum(byte[] data)
{
long sum = 0;
int length = data.Length;
int index = 0;
while (length > 1)
{
sum += (ushort)(((data[index] 0)
{
sum += (ushort)((data[index] > 16) != 0)
{
sum = (sum & 0xFFFF) + (sum >> 16);
}
// Return one's complement of the result
return (ushort)~sum;
}
Подробнее здесь: https://stackoverflow.com/questions/785 ... byte-array