Close UDP socket without socket .close ()

Having a python program that opens a UDP socket

receiveSock = socket(AF_INET, SOCK_DGRAM)
receiveSock.bind(("", portReceive))

      

Sometimes it happens that the program fails or I terminate it while it is running and it does not reach

receiveSock.close()

      

So the next time I try to run this program, I get

receiveSock.bind(("",portReceive))
  File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use

      

How can I close this socket using a shell command (or any other helpful idea)?

+3


source to share


1 answer


You have two options:

try:
   # your socket operations
finally:
   # close your socket

      

Or, for newer Python versions:



with open_the_socket() as the_socket:
   # do stuff with the_socket

      

with statement

will close the socket when the block is finished or the program exits.

+4


source







All Articles