为什么我在 Python 中收到错误“连接被拒绝”?(插座)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16130786/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:49:39  来源:igfitidea点击:

Why am I getting the error "connection refused" in Python? (Sockets)

pythonsockets

提问by Sheldon

I'm new to Sockets, please excuse my complete lack of understanding.

我是 Sockets 的新手,请原谅我完全缺乏理解。

I have a server script(server.py):

我有一个服务器脚本(server.py):

#!/usr/bin/python

import socket #import the socket module

s = socket.socket() #Create a socket object
host = socket.gethostname() #Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) #Bind to the port

s.listen(5) #Wait for the client connection
while True:
    c,addr = s.accept() #Establish a connection with the client
    print "Got connection from", addr
    c.send("Thank you for connecting!")
    c.close()

and client script (client.py):

和客户端脚本(client.py):

#!/usr/bin/python 

import socket #import socket module

s = socket.socket() #create a socket object
host = '192.168.1.94' #Host i.p
port = 12397 #Reserve a port for your service

s.connect((host,port))
print s.recv(1024)
s.close

I go to my desktop terminal and start the script by typing:

我转到我的桌面终端并通过键入以下内容启动脚本:

python server.py

after which, I go to my laptop terminal and start the client script:

之后,我转到我的笔记本电脑终端并启动客户端脚本:

python client.py

but I get the following error:

但我收到以下错误:

File "client.py", line 9, in

s.connect((host,port))

File "/usr/lib/python2.7/socket.py", line 224, in meth

return getattr(self._sock,name)(*args)

socket.error: [Errno 111] Connection refused

文件“client.py”,第 9 行,在

s.connect((主机,端口))

文件“/usr/lib/python2.7/socket.py”,第 224 行,在 meth 中

返回 getattr(self._sock,name)(*args)

socket.error: [Errno 111] 连接被拒绝

I've tried using different port numbers to no avail. However, I was able to get the host name using the same ip and the gethostname() method in the client script and I can ping the desktop (server).

我试过使用不同的端口号无济于事。但是,我能够在客户端脚本中使用相同的 ip 和 gethostname() 方法获取主机名,并且可以 ping 桌面(服务器)。

采纳答案by glglgl

Instead of

代替

host = socket.gethostname() #Get the local machine name
port = 12397 # Reserve a port for your service
s.bind((host,port)) #Bind to the port

you should try

你应该试试

port = 12397 # Reserve a port for your service
s.bind(('', port)) #Bind to the port

so that the listening socket isn't too restricted. Maybe otherwise the listening only occurs on one interface which, in turn, isn't related with the local network.

这样侦听套接字就不会受到太大限制。否则,侦听仅发生在一个接口上,而该接口又与本地网络无关。

One example could be that it only listens to 127.0.0.1, which makes connecting from a different host impossible.

一个例子可能是它只监听127.0.0.1,这使得从不同的主机连接是不可能的。

回答by SpankMe

This error means that for whatever reason the client cannot connect to the port on the computer running server script. This can be caused by few things, like lack of routing to the destination, but since you can ping the server, it should not be the case. The other reason might be that you have a firewall somewhere between your client and the server - it could be on server itself or on the client. Given your network addressing, I assume both server and client are on the same LAN, so there shouldn't be any router/firewall involved that could block the traffic. In this case, I'd try the following:

此错误意味着无论出于何种原因,客户端都无法连接到运行服务器脚本的计算机上的端口。这可能是由少数原因引起的,例如缺少到目的地的路由,但由于您可以 ping 服务器,因此不应该是这种情况。另一个原因可能是您的客户端和服务器之间有防火墙 - 它可能在服务器本身或客户端上。鉴于您的网络寻址,我假设服务器和客户端都在同一个 LAN 上,因此不应该涉及任何可能阻止流量的路由器/防火墙。在这种情况下,我会尝试以下操作:

  • check if you really have that port listening on the server (this should tell you if your code does what you think it should): based on your OS, but on linux you could do something like netstat -ntulp
  • check from the server, if you're accepting the connections to the server: again based on your OS, but telnet LISTENING_IP LISTENING_PORTshould do the job
  • check if you can access the port of the server from the client, but not using the code: just us the telnet (or appropriate command for your OS) from the client
  • 检查您是否真的有该端口在服务器上侦听(这应该告诉您代码是否按照您的想法执行):基于您的操作系统,但在 linux 上,您可以执行类似的操作 netstat -ntulp
  • 从服务器检查,如果您接受与服务器的连接:再次基于您的操作系统,但telnet LISTENING_IP LISTENING_PORT应该完成这项工作
  • 检查您是否可以从客户端访问服务器的端口,但不能使用代码:只需使用来自客户端的 telnet(或适用于您的操作系统的命令)

and then let us know the findings.

然后让我们知道调查结果。

回答by aoniao

host = socket.gethostname()  # Get the local machine name
port = 12397                 # Reserve a port for your service
s.bind((host,port))          # Bind to the port

I think this error may related to the DNS resolution. This sentence host = socket.gethostname()get the host name, but if the operating system can not resolve the host name to local address, you would get the error. Linux operating system can modify the /etc/hostsfile, add one line in it. It looks like below( 'hostname' is which socket.gethostname()got).

我认为此错误可能与 DNS 解析有关。这句话host = socket.gethostname()获取主机名,但是如果操作系统无法将主机名解析为本地地址,则会出现错误。Linux 操作系统可以修改该/etc/hosts文件,在其中添加一行。它看起来像下面('主机名'是socket.gethostname()得到的)。

127.0.0.1   hostname

回答by M Shiraz Baig

Assume s = socket.socket() The server can be bound by following methods: Method 1:

假设 s = socket.socket() 可以通过以下方法绑定服务器: 方法一:

host = socket.gethostname()
s.bind((host, port))

Method 2:

方法二:

host = socket.gethostbyname("localhost")  #Note the extra letters "by"
s.bind((host, port))

Method 3:

方法三:

host = socket.gethostbyname("192.168.1.48")
s.bind((host, port))

If you do not exactly use same method on the client side, you will get the error: socket.error errno 111 connection refused.

如果您没有在客户端完全使用相同的方法,您将收到错误: socket.error errno 111 connection refused.

So, you have to use on the client side exactly same method to get the host, as you do on the server. For example, in case of client, you will correspondingly use following methods:

因此,您必须在客户端使用与在服务器上完全相同的方法来获取主机。例如,在客户端的情况下,您将相应地使用以下方法:

Method 1:

方法一:

host = socket.gethostname() 
s.connect((host, port))

Method 2:

方法二:

host = socket.gethostbyname("localhost") # Get local machine name
s.connect((host, port))

Method 3:

方法三:

host = socket.gethostbyname("192.168.1.48") # Get local machine name
s.connect((host, port))

Hope that resolves the problem.

希望能解决问题。

回答by Majd Saadaoui

in your server.py file make : host ='192.168.1.94'instead of host = socket.gethostname()

在你的 server.py 文件中 make :host ='192.168.1.94'而不是host = socket.gethostname()

回答by mou ayad

try this command in terminal:

在终端中试试这个命令:

sudo ufw enable
ufw allow 12397

回答by Azizbro

I was being able to ping my connection but was STILL getting the 'connection refused' error. Turns out I was pinging myself! That's what the problem was.

我能够 ping 我的连接,但仍然收到“连接被拒绝”错误。原来我是在 ping 自己!这就是问题所在。