I'm not sure I fully understand your question, but here is the implementation of the echo server datagram that I just wrote. You can see that the server is responding to the client on the same IP / PORT from which it was sent.
Here is the code
First, the server (listener)
from socket import * import time class Listener: def __init__(self, port): self.port = port self.buffer = 102400 def listen(self): sock = socket(AF_INET, SOCK_DGRAM) sock.bind(('', self.port)) while 1: data, addr = sock.recvfrom(self.buffer) print "Received: " + data print "sending to %s" % addr[0] print "sending data %s" % data time.sleep(0.25)
And now the Client (sender), which receives a response from the Listener
from socket import * from time import sleep class Sender: def __init__(self, server): self.port = 1975 self.server = server self.buffer = 102400 def sendPacket(self, packet): sock = socket(AF_INET, SOCK_DGRAM) sock.settimeout(10.75) sock.sendto(packet, (self.server, int(self.port))) while 1: print "waiting for response" data, addr = sock.recvfrom(self.buffer) sock.close() return data if __name__ == "__main__": s = Sender("127.0.0.1") response = s.sendPacket("Hello, world!") print response
source share