Valhalla Legends Forums Archive | Battle.net Bot Development | [Python] udp checksum

AuthorMessageTime
aton
in case someone is interested...
[code]
    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
[/code]
July 4, 2009, 5:36 PM
xpeh
Ehm why can't you do like this?

[code]       
        #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
[/code]
July 5, 2009, 1:44 AM
xpeh
I simplified this algo even more.

[code]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;
}
[/code]

In python it will see like this
[code]
  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
[/code]
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.
July 5, 2009, 3:33 AM
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)
July 5, 2009, 12:18 PM
chyea
ew @ your spacing habits!
July 5, 2009, 9:21 PM

Search