User`s guide

KwikNet Low Level Services
K
A
DAK
149
kn_cksum kn_cksum
Purpose Compute an IP Checksum
Used by
n Task o ISP o Timer Procedure o Restart Procedure o Exit Procedure
Setup Prototype is in file KN_API.H.
#include "KN_LIB.H"
unsigned short kn_cksum(void *p, unsigned int n);
Description P is a pointer to a 16-bit aligned region of memory containing an array of
16-bit unsigned short integers to be checksummed.
N is the number of 16-bit unsigned short integers in the memory array
referenced by pointer p.
Returns The 16-bit, unsigned IP checksum of the n unsigned short integers in the
memory array referenced by pointer p. Note that the computed checksum
is not complemented before being returned to the caller.
Each 16-bit, unsigned short integer is added to the checksum using ones
complement arithmetic. Any overflow (carry) from the 16-bit checksum
is repetitively added to the checksum until no further overflow occurs.
The algorithms used by KwikNet to implement this procedure are both
processor and compiler dependent. The procedure has been coded for
fastest possible execution. If the C compiler supports the use of assembly
language within C, the procedure is coded in C using assembly language
statements of the form supported by the C compiler. Otherwise, the
function is coded reasonably efficiently using only C language statements.
Note The checksum algorithm is impervious to the processor's endianness.
Hence the 16-bit IP checksum can be stored into and read from the IP
packet header without conversion between net and host endianness as
illustrated in the example.
Example #include "kn_lib.h"
unsigned short cksum; /* Computed checksum */
unsigned short pktsum; /* Packet checksum */
unsigned short *p; /* IP header pointer */
pktsum = *(p + 5); /* Save IP header checksum */
*(p + 5) = 0; /* Checksum=0inpacket */
/* Compute IP header checksum*/
/* Length = IHL*2 shorts */
cksum = ~kn_cksum(p, (ntohs(*p) & 0x0F) << 1);
if (cksum != pktsum) {
kn_dprintf(0, "Received packet has checksum error.\n");
kn_dprintf(0, "Received %4X; expected %4X.\n",
ntohs(pktsum), ntohs(cksum));
}