| 1 | #!/usr/bin/env python |
|---|
| 2 | # -*- coding: utf-8 -*- |
|---|
| 3 | |
|---|
| 4 | # Copyright (C) 2008 Adriano Monteiro Marques. |
|---|
| 5 | # |
|---|
| 6 | # Author: Bartosz SKOWRON <getxsick at gmail dot com> |
|---|
| 7 | # |
|---|
| 8 | # This library is free software; you can redistribute it and/or modify |
|---|
| 9 | # it under the terms of the GNU Lesser General Public License as published |
|---|
| 10 | # by the Free Software Foundation; either version 2.1 of the License, or |
|---|
| 11 | # (at your option) any later version. |
|---|
| 12 | # |
|---|
| 13 | # This library is distributed in the hope that it will be useful, but |
|---|
| 14 | # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY |
|---|
| 15 | # or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public |
|---|
| 16 | # License for more details. |
|---|
| 17 | # |
|---|
| 18 | # You should have received a copy of the GNU Lesser General Public License |
|---|
| 19 | # along with this library; if not, write to the Free Software Foundation, |
|---|
| 20 | # Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
|---|
| 21 | |
|---|
| 22 | """ |
|---|
| 23 | Functions related to network issues. |
|---|
| 24 | """ |
|---|
| 25 | |
|---|
| 26 | import umpa.utils.bits |
|---|
| 27 | |
|---|
| 28 | def in_cksum(data, cksum=0): |
|---|
| 29 | """ |
|---|
| 30 | Return Internet Checksum. |
|---|
| 31 | |
|---|
| 32 | It is an implementation of RFC 1071. |
|---|
| 33 | |
|---|
| 34 | To check if the already calculated checksum is correct, pass it as cksum |
|---|
| 35 | argument. If the result is 0, then the ckecksum has not detected an error. |
|---|
| 36 | |
|---|
| 37 | @type data: C{int} |
|---|
| 38 | @param data: the data from which checksum is calculated. |
|---|
| 39 | |
|---|
| 40 | @type cksum: C{int} |
|---|
| 41 | @param cksum: already calculated checksum for comparision (default: 0) |
|---|
| 42 | |
|---|
| 43 | @rtype: C{int} |
|---|
| 44 | @return: calculated checksum. |
|---|
| 45 | """ |
|---|
| 46 | |
|---|
| 47 | pieces = umpa.utils.bits.split_number_into_chunks(data) |
|---|
| 48 | if len(pieces)%2 == 1: |
|---|
| 49 | pieces.append(0) |
|---|
| 50 | |
|---|
| 51 | for i in xrange(0, len(pieces), 2): |
|---|
| 52 | x = ((pieces[i] << 8) & 0xff00) + (pieces[i+1] & 0xff) |
|---|
| 53 | cksum += x |
|---|
| 54 | |
|---|
| 55 | while cksum >> 16: |
|---|
| 56 | cksum = (cksum & 0xffff) + (cksum >> 16) |
|---|
| 57 | |
|---|
| 58 | cksum = ~cksum |
|---|
| 59 | return int(cksum & 0xffff) |
|---|