Valhalla Legends Archive

Programming => Battle.net Bot Development => Topic started by: aton on July 04, 2009, 12:36 PM

Title: [Python] udp checksum
Post by: aton on July 04, 2009, 12:36 PM
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
Title: Re: [Python] udp checksum
Post by: xpeh on July 04, 2009, 08:44 PM
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
Title: Re: [Python] udp checksum
Post by: xpeh on July 04, 2009, 10:33 PM
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.
Title: Re: [Python] udp checksum
Post by: aton on July 05, 2009, 07:18 AM
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)
Title: Re: [Python] udp checksum
Post by: bulletproof tiger on July 05, 2009, 04:21 PM
ew @ your spacing habits!