Python TypeError: an integer is required while working with Sockets

mee picture mee · Jan 28, 2015 · Viewed 17.8k times · Source

Research:

Getting a "TypeError: an integer is required" in my script

https://github.com/faucamp/python-gsmmodem/issues/39

https://docs.python.org/2/howto/sockets.html

Here is my complete error output:

Traceback (most recent call last):
File "/home/promitheas/Desktop/virus/socket1/socket1.py", line 20, in <module>
createSocket()
File "/home/promitheas/Desktop/virus/socket1/socket1.py", line 15, in    createSocket
ServerSock.bind((socket.gethostname(), servPort))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
TypeError: an integer is required

Code:

import socket

# Acquiring the local public IP address
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 0))

# Defining some variables
servIpAddr = s.getsockname()[0]
servPort = ''
while ((len(servPort) < 4)): # and (len(servPort) > 65535)
    servPort = raw_input("Enter server port. Must be at least 4     digits.\n> ")

# Creating a socket to wait for a connection
def createSocket():
    ServerSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    ServerSock.bind((socket.gethostname(), servPort)) # This is where the error occurs
    ServerSock.listen(5)
    (clientsocket, address) = ServerSock.accept()

if __name__ == "__main__":
    createSocket()

I'm not sure if there are any other errors, but I'm really stumped on this one. Please ask if you need any other info, and thanks in advance!

Answer

Kevin picture Kevin · Jan 28, 2015

It looks like the second element of the address tuple needs to be an integer. From the documentation:

A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer.

Try converting servPort to an integer before using it in bind.

servPort = ''
while ((len(servPort) < 4)): # and (len(servPort) > 65535)
    servPort = raw_input("Enter server port. Must be at least 4     digits.\n> ")
servPort = int(servPort)