How to shutdown udp socket in python

Viewed 3332

I have a socket listener thread running and it supposed to close when a particular condition is met.here is my code snippet.

 def __init__(self, arg):

        threading.Thread.__init__(self)
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        receiver_port = int(<port>)
        listen_addr = (<some ip>, receiver_port)
        self.socket.bind(listen_addr)
        self.shutdown = threading.Event()
        self.shutdown.set()

 def kill_function():

       self.socket.shutdown(socket.SOCK_DGRAM)
       self.shutdown.clear()
       self.socket.close()

I am facing

OSError: [Errno 107] Transport endpoint is not connected error when I try to 
kill the socket.

The same issue is observing if I user SHUT_RD, SHUT_RDWR. can anyone please help me how to call shutdown() function, while using UDP sockets.

Thanks in advance.

1 Answers
self.socket.shutdown(socket.SOCK_DGRAM)

shutdown is not relevant for UDP sockets but for TCP. And, shutdown takes only arguments on how to shutdown (SHUT_RD, SHUT_WR, SHUT_RDWR) and not a protocol as you do.

Apart from that, your code binds the UDP socket to a local address but does not connect it to another address, i.e. it can send anywhere using socket.sendto. Thus you get the message that the socket is not connected when trying to shut a non-existing connection down.

Related