Reputation: 81
I have a Python Socket server
program, and for whatever reason the program can't bind the host and port together.
Here's my code:
import socket
import sys
host = ""
port = 9999
s = socket.socket()
try:
("Binding socket to port: " + str(port))
s.bind((host, 9999))
s.listen(5)
except socket.error as msg:
print("Socket binding error: " + str(msg) + "\n" + "Retrying...")
conn, address = s.accept()
print("Connection has been established: " + "IP " + address[0] + " Port " + str(address[1]))
while True:
cmd = input()
if cmd == "quit":
conn.close()
s.close()
sys.exit()
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
client_response = str(conn.recv(1024), "utf-8")
print(client_response, end=="")
conn.close()
I've had it print the error, and it says: Socket binding error: [Errno 10048]
Only one usage of each socket address (protocol/network address/port)
is normally permitted.
Does anyone know what this means and what I should do?
Upvotes: 0
Views: 6589
Reputation: 81
Thanks guys. I figured out that I just needed to get a different port number; it is probably in use in some other program. That's a really cool suggestion about using the for loop to try to find an available port!
Upvotes: 1
Reputation: 93
Just guessing: But did you run the code before?
Because then you might not have come to perform the conn.close()
.
And therefore the port is still used (by your first run) when trying again.
On Linux you could find the python process by calling
lsof -i :9999
Upvotes: 1
Reputation: 69
That error message says the port is already in use (bound). It sounds like you've got a second copy of the program running that is already bound to port 9999. Try logging out or rebooting if you can't find another way to get rid of it.
Upvotes: 0