开发者

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. The code I've posted above works beautifully when the server is running on Arch Linux or Ubuntu. When it's on Windows 7 however, it only accepts local connections. 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! 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.

If it helps, on Arch and Ubuntu, I'm running on Python 3.1, while on Win 7 it's on 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).

To make your server reachable on all (IPv4) interfaces on the host, this should work on Linux, Windows, Mac, etc:

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:

Some behavior may be platform dependent, since calls are made to the operating system socket APIs.

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.

My suggestion is move up an abstraction level and use SocketServer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜