Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reuse the socket address python?

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?

like image 381
Nemi Bhattarai Avatar asked Mar 08 '23 07:03

Nemi Bhattarai


1 Answers

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?

like image 85
Tomasz Wiśniewski Avatar answered Mar 24 '23 14:03

Tomasz Wiśniewski