Python LogoA while back I showed you how to write a UDP client and server with C#. Just recently I had the need to do the same thing for a new program I am working on. However, the new application I am working on involves a Python server which will be running on a Linux machine. Because of this, the C# UDP server code is useless in my new app. So, I needed to write some code using Python that can listen for UDP broadcasts and even send back a reply to the client that submitted the broadcast. Even though I could test the UDP listener code using the C# client I showed before, I felt like I should still take it to the next step and go ahead and write a simple UDP client using Python as well. Now, I’m not going to tell you any details about the app that I’m working on. But, I have stripped out the UDP code since it’s extremely simple and can be found anywhere on the internet. I’ve had requests for this very code in the past. Now I want to share it with all of you that are interested. So, enjoy!

UDP Server:

import socket, traceback

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.bind(('', 5000))

print "Listening for broadcasts..."

while 1:
    try:
        message, address = s.recvfrom(8192)
        print "Got message from %s: %s" % (address, message)
        s.sendto("Hello from server", address)
        print "Listening for broadcasts..."
    except (KeyboardInterrupt, SystemExit):
        raise
    except:
        traceback.print_exc()

UDP Client:

import socket, sys
dest = ('<broadcast>', 5000)

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
s.sendto("Hello from client", dest)
print "Listening for replies; press Ctrl-C to stop."
while 1:
    (buf, address) = s.recvfrom(2048)
    if not len(buf):
        break
    print "Received from %s: %s" % (address, buf)
    break

Thank you for your interest in my site. If you find the information provided on this site useful, please consider making a donation to help continue development!

PayPal will open in a new tab.
$2.00
$5.00
Other

Related Posts

Tagged with:  

Leave a Reply