简体   繁体   English

Python TypeError:使用套接字时需要一个整数

[英]Python TypeError: an integer is required while working with Sockets

Research: 研究:

Getting a "TypeError: an integer is required" in my script 在我的脚本中获取“TypeError:需要一个整数”

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

https://docs.python.org/2/howto/sockets.html 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! 请询问您是否需要任何其他信息,并提前致谢!

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 . 一对(主机,端口)用于AF_INET地址族,其中host是一个字符串,表示Internet域符号中的主机名,如'daring.cwi.nl'或IPv4地址,如'100.50.200.5', port是整数

Try converting servPort to an integer before using it in bind . bind使用它之前,尝试将servPort转换为整数。

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)

servPort must be an integer. servPort必须是整数。 You currently have it set to a string the user enters. 您当前将其设置为用户输入的字符串。 Try casting the raw_input to an int using int(servPort) . 尝试使用int(servPort)将raw_input转换为int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM