How to reuse the socket address python?
Asked Answered
S

1

5

Here is server side code:

import socket
import sys

HOST = ''   # Symbolic name, meaning all available interfaces
PORT = 7800 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print ('Socket created')

#Bind socket to local host and port
try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print ('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print ('Socket now listening')

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print ('Connected with ' + addr[0] + ':' + str(addr[1]))
    msg = conn.recv(1024)
s.close()

whenever I use this code for the first time I can easily connect with the client and after second time I get the error "Only one usage of each socket address (protocol/network address/port) is normally permitted"

How could I modify the code that it will work again and again?

Shick answered 24/12, 2017 at 6:15 Comment(1)
If you are doing a while 1, how do you ever reach s.close ()?Benita
G
8

Try this line after creating s :

# ...
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# ...

Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?

Goar answered 24/12, 2017 at 9:6 Comment(2)
Thank you It worked but only in python 2.7 and not in python 3.5Shick
This works for me on Python 3.6. Docs: docs.python.org/3/library/socket.html#socket.socket.setsockopt (and thanks for the link to 14388706!)Testes

© 2022 - 2024 — McMap. All rights reserved.