TCPIPchecksum.cc

Go to the documentation of this file.
00001 //
00002 // Copyright (C) 2005 Christian Dankbar, Irene Ruengeler, Michael Tuexen, Andras Varga
00003 //               2009 Zoltan Bojthe
00004 //
00005 // This program is free software; you can redistribute it and/or
00006 // modify it under the terms of the GNU General Public License
00007 // as published by the Free Software Foundation; either version 2
00008 // of the License, or (at your option) any later version.
00009 //
00010 // This program is distributed in the hope that it will be useful,
00011 // but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013 // GNU General Public License for more details.
00014 //
00015 // You should have received a copy of the GNU General Public License
00016 // along with this program; if not, see <http://www.gnu.org/licenses/>.
00017 //
00018 
00019 #include "TCPIPchecksum.h"
00020 
00021 #if !defined(_WIN32) && !defined(__WIN32__) && !defined(WIN32) && !defined(__CYGWIN__) && !defined(_WIN64)
00022 #include <netinet/in.h>  // htonl, ntohl, ...
00023 #endif
00024 
00025 uint16_t TCPIPchecksum::_checksum(const void *addr, unsigned int count)
00026 {
00027     uint32_t sum = 0;
00028 
00029     while (count > 1)
00030     {
00031         sum += *((const uint16_t *&)addr)++;
00032         if (sum & 0x80000000)
00033             sum = (sum & 0xFFFF) + (sum >> 16);
00034         count -= 2;
00035     }
00036 
00037     if (count)
00038         sum += *(const uint8_t *)addr;
00039 
00040     while (sum >> 16)
00041         sum = (sum & 0xFFFF) + (sum >> 16);
00042 
00043     return (uint16_t)sum;
00044 }