简体   繁体   English

Python套接字只接受本地连接

[英]Python socket only accepting local connections

Server: 服务器:

import socket

host = ""
port = 4242
backlog = 5
size = 1024
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(backlog)
client, address = s.accept()
while 1:

    data = client.recv(size)
    if data:
        client.send(data)
        print(data.decode("utf-8"))

Client: 客户:

import socket
import sys

host = sys.argv[1]
port = 4242
size = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
while True:
    line = input("What to say: ")
    s.send(line.encode("utf-8"))

Well, I'm a bit confused here. 好吧,我在这里有点困惑。 I'm beginning to learn about sockets, so I started out on a simple echo server. 我开始学习套接字了,所以我开始使用一个简单的echo服务器。 The code I've posted above works beautifully when the server is running on Arch Linux or Ubuntu. 当服务器在Arch Linux或Ubuntu上运行时,我上面发布的代码可以很好地工作。 When it's on Windows 7 however, it only accepts local connections. 但是,当它在Windows 7上时,它只接受本地连接。 The thing is, I'm not running a firewall. 问题是,我没有运行防火墙。 I'm not sure if Python has a separate WinSock implementation or what, but I'm confused! 我不确定Python是否有单独的WinSock实现或什么,但我很困惑! Please, if you would, I'm quite aware that this is terribly designed (only accepts on client!), but I just want to know why Windows won't accept remote connections. 如果你愿意的话,我非常清楚这是非常设计的(只接受客户端!),但我只是想知道为什么Windows不接受远程连接。

If it helps, on Arch and Ubuntu, I'm running on Python 3.1, while on Win 7 it's on 3.2. 如果它有帮助,在Arch和Ubuntu上,我正在运行Python 3.1,而在Win 7上它运行在3.2。

Sounds like host='' is defaulting to bind to localhost (127.0.0.1) under Win 7 (I don't have access to a Win 7 machine at the moment). 听起来像host=''是默认绑定到Win 7下的localhost(127.0.0.1)(目前我无法访问Win 7机器)。

To make your server reachable on all (IPv4) interfaces on the host, this should work on Linux, Windows, Mac, etc: 要使服务器在主机上的所有(IPv4)接口上都可访问,这应该适用于Linux,Windows,Mac等:

host = '0.0.0.0'
s.bind((host, 8080))

To verify which address the socket is binding to you can do this: 要验证套接字绑定到哪个地址,可以执行以下操作:

>>> s.getsockname()
('0.0.0.0', 8080)

As the documentation for Socket states: 正如Socket的文档所述:

Some behavior may be platform dependent, since calls are made to the operating system socket APIs. 某些行为可能与平台有关,因为对操作系统套接字API进行了调用。

I'm not familiar with Win32 network programming, but I would hazard a guess that it's probably a implementation specific behavior that is triggered when you create a socket without binding it to an address. 我不熟悉Win32网络编程,但我猜测它可能是一种特定于实现的行为,当您创建套接字而不将其绑定到地址时会触发该行为。

My suggestion is move up an abstraction level and use SocketServer . 我的建议是提升抽象级别并使用SocketServer

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

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