// Calculate TCP checkcum
function RERFilter.RecalculateTCPChecksum(aLen: Integer;
aSrcAddr, aDstAddr: Cardinal;
buff: PByteArray): Word;
type
Tbyte = array of byte;
var
w16,padd: word;
i,sum: integer;
sIP,dIP: in_addr;
begin
padd := 0;
sum := 0;
try
try
if (aLen div 2) * 2 <> aLen then begin
padd := 1;
buff[aLen] := 0;
end;
i := 0;
while i < aLen+padd do begin
w16 := ((buff[i] shl 8)and $FF00) + (buff[i+1]and $FF);
sum := sum + integer(w16);
i := i + 2;
end;
//add IP length
sIP := in_addr(aSrcAddr);
dIP := in_addr(aDstAddr);
sum := sum + ntohs(sIP.S_un_w.s_w1) + ntohs(sIP.S_un_w.s_w2);
sum := sum + ntohs(dIP.S_un_w.s_w1) + ntohs(dIP.S_un_w.s_w2);
sum := sum + IPPROTO_TCP + word(aLen);
while (sum shr 16)>0 do
sum := (sum and $FFFF)+(sum shr 16);
sum := not sum;
except on E : Exception do
MessageDlg('Error Calculating TCP Checksum.'+#10#13+
'Exception: '+E.Message, mtError, [mbOk], 0);
end;
finally
Result := sum;
end;
end;
|