Reputation:
guys, I am trying to work on a simple chat tcp server that allows messages to be sent back in forth from the server and the client. I have to make it so that the port number is entered in on the command line instead of hardcoded in. I have tried multiple things but this is my most recent effort. I am getting errors about portnum not being an integer, and
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
s.bind((socket.gethostname(), 1234))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"Connection from {address} has been established")
clientsocket.send(bytes("Welocme to the server","utf-8"))
and here is what I tried changing it too
portnum = input("Enter port number")
s.bind((socket.gethostname(), portnum))
s.listen(5)
I have also tried doing :
port = sys.argv[1:] and port = int(sys.argv[1])
but I keep getting errors and it isn't working
Upvotes: 0
Views: 692
Reputation: 344
input
will always cast the user's input to a string. https://docs.python.org/3/library/functions.html#input
You should add a check to validate the input is numeric, cast it to an int
and pass it as the port number.
while True:
portnum = input("Enter port number")
if portnum.isnumeric():
portnum = int(portnum)
s.bind((socket.gethostname(), portnum))
s.listen(5)
...
else:
print("Enter a valid port number.")
Upvotes: 1