• Welcome to Valhalla Legends Archive.
 

[Python] udp checksum

Started by aton, July 04, 2009, 12:36 PM

Previous topic - Next topic

aton

in case someone is interested...

    def checksum(self, data):
        """ calculates the battle.net udp checksum
            in: data(str), checksum doesnt matter
            out: cksum(str)
        """
        sum1=0
        sum2=0
       
        buf="\x00\x00" # null checksum
        buf+=data[6:] # dont copy leading 4 zeroes and old checksum
   
        for i in range(len(buf), 2, -1):
            sum2+=ord(buf[i-1])
            if sum2>0xff:
                sum2-=0xff
            sum1+=sum2
       
        subsum=long( ((sum2&0xff)<<8) | ((sum1%0xff) & 0xff) )
        a=long( 0xff - ((subsum&0xff) + (subsum>>8)) % 0xff )
        b=long( ((((0xff - (a+(subsum>>8))%0xff) &0xff) | (a<<8))) )
        ret=""
        ret+=chr(b&0x00ff)
        ret+=chr((b&0xff00)>>8)
       
        return ret

xpeh

Ehm why can't you do like this?

       
        #buf="\x00\x00" # null checksum
        #buf+=data[6:] # dont copy leading 4 zeroes and old checksum
   
        for i in range(len(data), 6, -1):
                # now use data instead of buf

xpeh

#2
I simplified this algo even more.

sub scgp_checksum { my ($packet) = @_;
   my $a = 0; my $b = 0;
   for (my $i = length ($packet) - 1; $i >= 6; $i--) { # process from end to the 6th byte
       $b += ord(substr($packet, $i, 1));
       $a += $b;
   }
   my $a2 = 0xff - ($a + $b) % 0xff;
   return ($a % 0xff | ($a2 * 256)) & 0xffff;
}


In python it will see like this

  def checksum(self, data):
       """ calculates the battle.net udp checksum
           in: data(str), checksum doesnt matter
           out: cksum(str)
       """
       sum1=0
       sum2=0
       for i in range(len(data), 6, -1):
           sum2+=ord(data[i-1])
           sum1+=sum2
       a2 = 0xff - (sum1 + sum2) % 0xff
       return (sum1 % 0xff | a2 * 256) & 0xffff

I didnt tested it on more than 1 packet. So proove it by yourself :)

Why do you need long() in your code?

Edit: small error in python code. Better dont rely on it since i didnt tested it,  convert it prom perl code.

aton

heh nice work, if it works.

i didnt care to simplify it, i just took the c function and translated it line by line (more or less)

bulletproof tiger

ew @ your spacing habits!