Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Close UDP socket with no socket.close()

Having a python program which open UDP socket

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

It sometimes happens that the program fails or I terminate it in running time and it doesn't reach to

receiveSock.close()

So that at the next time I trying to run this program I get

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

How could I close this socket using shell command (or any other useful idea)?

like image 908
URL87 Avatar asked Oct 05 '22 07:10

URL87


1 Answers

You have two options:

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

Or, for newer versions of Python:

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

The with statement will close the socket when the block is finished, or the program exits.

like image 78
Burhan Khalid Avatar answered Oct 08 '22 07:10

Burhan Khalid