2

I want a Python program that I am writing to use a port to communicate with another program. I'm having a lot of trouble with sockets, but the main problem is that I can't reuse ports as I debug my program.

Here is the part of the code where I create the socket:

# create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_address = ("localhost", 10000)
sock.bind(server_address)
# listen for activity
sock.listen(1)

The program usually crashes when I try doing things after this point. If I try rerunning it, I get the "Address already in use" error. The only fixes I have are closing my IDE and reopening or changing which ports the programs use to communicate. I noticed that after the program crashes, it's still listening on the port.

COMMAND  PID     USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
java    1981 ********  139u  IPv6 0x9b8f5bc88c24993f      0t0  TCP localhost:ndmp (LISTEN)

(It says Java because I'm running my program from a Jython environment.)

Is there anything I can do on the Python side so that I can just rerun my program?

alternum5
  • 75
  • 8
  • 3
    Maybe [\[SO\]: Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?](https://stackoverflow.com/questions/14388706/socket-options-so-reuseaddr-and-so-reuseport-how-do-they-differ-do-they-mean-t) would help. – CristiFati Oct 20 '17 at 20:05
  • In sounds like in your environment `sock` is still open. If you are in an IDE that is still open after the crash, executing `sock.close()` could fix the issue. – Mark Tolonen Oct 20 '17 at 23:08
  • I ended up just putting the offending block of code in a try block. – alternum5 Nov 11 '17 at 19:33

0 Answers0