All pastes #180482 Raw Edit

Cody Brocious

public python v1 · immutable
#180482 ·published 2006-09-23 06:32 UTC
rendered paste body
#!/usr/bin/env pythonimport socket, struct, sysdef hexDump(data):    ret = ''    for i in range(0, len(data), 16):        ret += '%08x | ' % i        for j in range(16):            if j == 8:                ret += ' '            if len(data) > i + j:                ret += '%02X ' % ord(data[i + j])            else:                ret += '   '        ret += ' | '        for j in range(16):            if j == 8:                ret += '  '            if len(data) > i + j:                c = data[i + j]                if ord(c) > 31 and ord(c) < 127:                    ret += c                else:                    ret += '.'            else:                ret += ' '        ret += '\n'    return retclass SLPacket(object):    def __init__(self):        self.flags = None        self.seq = None        self.opcode = None        self.data = None            def unpack(self, packet):        self.flags = struct.unpack('<H', packet[0:2])[0]        self.seq = struct.unpack('<H', packet[2:4])[0]        if packet[4] == '\xFF':            if packet[5] == '\xFF':                self.opcode = struct.unpack('>L', packet[4:8])[0]                start = 8            else:                self.opcode = struct.unpack('>H', packet[4:6])[0]                start = 6        else:            self.opcode = ord(packet[4])            start = 5        self.data = packet[start:]        return self            def __str__(self):        return 'Flags: %04X Seq: %04X Opcode: %08X \n%s' % (self.flags, self.seq, self.opcode, hexDump(self.data))class UDPDumper:    def __init__(self, port):        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)        self.sock.bind(('', port))        while True:            data, addr = self.sock.recvfrom(65536)            print 'Received packet from %s:' % `addr`            print SLPacket().unpack(data)if __name__=='__main__':    UDPDumper(port=12036)