尝试连接套接字时出现错误 10051 [英] Error 10051 while trying to connect socket
问题描述
我最近在 linux 中构建了一个套接字服务器聊天.
I recently built a socket-server chat in linux.
当我尝试连接我的 windows 8.1 主计算机(都在同一子网下)时,我得到:
When I try to connect my windows 8.1 main computer (Both under the same subnet), i get an:
[Errno 10051]: A socket operation was attempted to an unreachable network
代码:
import socket
import datetime
import getpass # Get username
import sys
import thread
import select
def client():
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(("127.0.0.1", 8856))
sock.connect(("192.168.1.17", 23657))
sock.send(getpass.getuser()+"[$ID$]4sthg")
socket_list = [sys.stdin, sock]
partner = raw_input("Chat partner: ")
while 1:
# Get the list sockets which are readable
read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])
for sock_index in read_sockets:
# incoming message from remote server
if sock_index == sock:
data = sock_index.recv(4096)
if not data :
print '\nDisconnected from chat server'
sys.exit()
else :
#print data
sys.stdout.write(data)
# user entered a message
else:
msg = sys.stdin.readline()
sock.send(partner + "|" + msg)
def get_time():
return datetime.datetime.strftime(datetime.datetime.now(), '%H:%M:%S')
def main():
client()
if __name__ == "__main__":
main()
我尝试ping"到我的笔记本电脑地址,效果很好.还在我的 linux 防火墙中添加了一条规则,声明允许来自我的 Windows 计算机的每个数据包.
I tried "ping" to my laptop address, and it worked well. also added a rule in my linux firewall, declares that every packet comes from my windows computer is allowed.
知道为什么会这样吗?
谢谢!
推荐答案
行:
sock.bind(("127.0.0.1", 8856))
是错误的 - 您绑定到 loopback
虚拟接口,因此只允许本地(同一台机器)对等方与您交谈.
is wrong - you are binding to the loopback
virtual interface, thus only allowing local (same machine) peers to talk to you.
实际上,当你连接出来时,即作为一个普通的 TCP 客户端,你根本不应该绑定套接字的本地端.内核 TCP/IP 堆栈将为套接字分配一个临时端口
,路由表将规定用于传出连接的网络接口.
In fact, when you connect out, i.e. act as a normal TCP client, you should not bind the local end of the socket at all . Kernel TCP/IP stack will assign an ephemeral port
to the socket, and the routing table will dictate what network interface to use for outgoing connection.
同样,SO_REUSEADDR
选项仅用于侦听服务器:
On the same note, the SO_REUSEADDR
option is only needed for listening servers:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
删除这两行并重试.
这篇关于尝试连接套接字时出现错误 10051的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!