Подскажите, пожалуйста, алгоритм подсчета контрольной суммы IP заголовка.
ChecksumAs a precaution against corruption by routers, there is a checksum for the IP header. The steps for
transmission are as follows.
1. Prepare and byte swap the header.
2. If it is an odd length, pad with a zero byte.
3. Clear the checksum field.
4. Sum the 16-bit words in the header.
5. Put the one's complement of the result in the checksum field.
The addition is somewhat unusual, in that any carry bits are added back on.
Код
long sum;
WORD *data;
sum += *data++;
if (sum & 0x10000L)
sum = (sum & 0xffffL) + 1;
This addition method is particularly suitable for implementation in assembly language because it is just a
repeated add-with-carry, irrespective of whether a big endian or little endian processor is being used. There
is a useful optimization to the C version, which involves saving up the carry bits then adding them on at the
end.
Код
/* Do checksum. Improved algorithm is from RFC 1071 */
WORD csum(void *dp, WORD count)
{
register LWORD total=0L;
register WORD n, *p, carries;
n = count / 2;
p = (WORD *)dp;
while (n--)
total += *p++;
if (count & 1)
total += *(BYTE *)p;
while ((carries=(WORD)(total >>16))!=0)
total = (total & 0xffffL) + carries;
return((WORD)total);
}
This also caters to an odd length by doing an extra single-byte addition (little endian processors only). On
reception, the datagram header is verified by applying the checksum across it; the result should be FFFFh.