首页 > 解决方案 > Python 套接字侦听失败,错误目标机器主动拒绝它

问题描述

我已经通过运行这个 python 脚本

python myproxy.py

我收到以下错误:

Traceback (most recent call last):
  File "proxy.py", line 4, in <module>
    client_socket.connect(('localhost', 5000))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

脚本:

import socket, time

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(('localhost', 5000))
serversocket.listen(20) # become a server socket, maximum 20 connections

while True:
    connection, address = serversocket.accept()
    data = client_socket.recv(512)
    print("RECEIVED: %s" % data)
    client_socket.send(data)

有很多关于这是防火墙问题的 stackoverflow 答案。我创建了一个传入和传出防火墙规则以允许端口 5000 并且没有工作。请不要链接这些问题,与以前的问题不同,让我们避免让彼此失望。

我不是 telnet 专家,但我尝试过:

远程登录

Welcome to Microsoft Telnet Client

Escape Character is ']'

Microsoft Telnet> open localhost 5000
Connecting To localhost...Could not open connection to the host, on port 5000: Connect failed
Microsoft Telnet> open 127.0.0.1 5000
Connecting To 127.0.0.1...Could not open connection to the host, on port 5000: Connect failed
Microsoft Telnet>

我也在使用代理。我关闭了没有解决这个问题的代理。一般来说,我更喜欢在使用代理时使用此脚本,但如果没有其他选项,关闭代理也可以。

我应该如何解决这个问题?

更新:

使用

client_socket.connect((socket.gethostbyname(socket.gethostname()), 5000))

没有太大帮助:

    client_socket.connect((socket.gethostbyname(socket.gethostname()), 5000))
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it

标签: pythonpython-3.xwindowssockets

解决方案


尝试用 socket.gethostbyname(socket.gethostname()) 替换 'localhost'
你还需要 serversocket 在服务器脚本中。


推荐阅读