Handling errors in a Python UDP proxy The following (stripped) program receives UDP packets on port 5000 and forwards them to port 5001. It may throw socket errors on startup (e.g.: if the port is already in use), but I am not too worried about that.

import socket

RECEIVE_IP = "0.0.0.0"
RECEIVE_PORT = 5000
RECEIVE_BUFFER_SIZE = 4096

SEND_IP = "127.0.0.1"
SEND_PORT = 5001

send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

receive_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
receive_socket.bind((RECEIVE_IP, RECEIVE_PORT))

while True:
    string = receive_socket.recv(RECEIVE_BUFFER_SIZE)
    send_socket.sendto(string, (SEND_IP, SEND_PORT))


I would like to make sure the program keeps running after a successful startup. Is it enough to try/catch the socket errors?

while True:
    try:
        string = receive_socket.recv(RECEIVE_BUFFER_SIZE)
        send_socket.sendto(string, (SEND_IP, SEND_PORT))
    catch socket.error:
        print 'Oops!'


Or is there anything else I need to worry about? Would I ever need to rebind receive_socket for instance?

Bonus question: the real problem here is that I am not aware how to test this program for failure. Would anyone have a recommendation?
On the face of it, what you're suggesting seems like it should work (although it may be implementation dependant since it depends on the OS socket API).  It also depends on what you mean by 'stripped down'.  Obviously, if you're doing something with the received packets that might throw an error you'll need to handle that as well.  Your catch would be better written as:

except socket.error:
    print ('Oops!')


As far as testing goes, you're sending to the same IP address so should be pretty safe but some things to try are:


Pull out / reconnect network cables
Turn off / reenable Wi-Fi
Disable / reenable network adapters
Send unexpectedly large packets (over your 4096 buffer size)
Try running multiple clients in constant send loops to see how your app handles large demand.