Search code examples
python-3.xsocketsnetwork-programmingbind

Why does socket.bind() expect an integer here?


I'm very new to networking programming. I'm trying to setup a web server and I'm trying to bind the welcoming socket to the localhost address and an arbitrary port number that's passed as the command line argument. However, the socket.bind() method just keeps giving me errors saying it's expecting an integer instead of a string when, as far as I can tell from the documentation, the host address is supposed to be a string.

I've tried gethostname, gethostbyname and a combination of the two to resolve this error but nothing seems to work.

This is a snippet of the program I've written:

from socket import *
import sys

port_number = sys.argv[1]
server_sock = socket(AF_INET, SOCK_STREAM)
host = gethostbyname(gethostname())
print(host)
server_sock.bind((host, port_number))
server_sock.listen(1)
print('The server is online.')

To be exact, this is the error I get: "TypeError: an integer is required (got type str)"

How do I fix this?


Solution

  • The port needs to be an integer, so convert the string port_number to an integer:

    server_sock.bind((host, int(port_number)))