UDP socket, the solution

Sells, Fred fred at adventistcare.org
Wed Jan 4 16:27:25 EST 2006


import socket, threading, time, binascii, struct
from Configure import Debug
thanks to all, here's my final code that works, if it helps anyone


import socket, threading, time, binascii, struct
from Configure import Debug

ZERO = chr(0)

class Udp:

    def __init__(self, my_address, destination_address, timeout=2.0,
log=None):
        self.MyAddress = my_address  #(ip,port)
        self.Destination = destination_address #(ip,port)
        self.Socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.Socket.settimeout(timeout)
        self.Socket.bind(self.MyAddress)
        self.log = log

    def sendto(self, msg):
        nsent = self.Socket.sendto(msg, self.Destination)
        if Debug.Udp: print >>Debug.Log, '\t\t\t\t   ==>', self.format(msg,
send=True)
        return nsent

    def recvfrom(self, size=4096):
	data, addr = self.Socket.recvfrom(size)
        if self.log: print >>self.log, '\t\t\t\t<==   ', self.format(data,
send=False)
	return data

    def format(self, x, send):
        first = struct.unpack('>BBI', x[:6])
        tmp = ' ctrl=%02x %02x n=%08x  ' % first
        if len(x)>6:
            if x[-1]==ZERO:
                tmp += '  data="%s x00"' % x[6:-1]
            else:
                tmp += '  data="%s"' % x[6:]
        return tmp
        

if __name__=='__main__':
    syncmsg = struct.pack('>BBI', 8, 0x4a, 0xaabbccdd)
    S = Udp( ('192.168.201.171', 1201) , ('192.168.201.72', 1202))
    response = S.sendto(syncmsg)
    x = S.recvfrom()
    print x



---------------------------------------------------------------------------
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---------------------------------------------------------------------------



More information about the Python-list mailing list