Keepalived系列2:IP报文的校验计算

int in_cksum(register unsigned short *ptr , int nbytes)
{
  register long sum;
  u_short oddbyte;
  register u_short answer;

  sum = 0;
  while (nbytes > 1)  {
    sum += *ptr++;
    nbytes -= 2;
  }

  /* mop up an odd byte, if necessary */
  if (nbytes == 1) {
    oddbyte = 0;                                /* make sure top half is zero */
    *((u_char *) &oddbyte) = *(u_char *)ptr;    /* one byte only */
    sum += oddbyte;
  }

  /* Add back carry outs from top 16 bits to low 16 bits. */
  sum  = (sum >> 16) + (sum & 0xffff);  /* add high-16 to low-16 */
  sum += (sum >> 16);                   /* add carry */
  answer = ~sum;                        /* ones-complement, then truncate to 16 bits */
  return(answer);
}

留着,以后不用自己写了。

你可能感兴趣的:(keepalived)