我有什么主机绑定侦听套接字?

low*_*key 4 python sockets networking network-programming

我使用了python的套接字模块并尝试使用开启监听套接字

import socket
import sys

def getServerSocket(host, port):
    for r in socket.getaddrinfo(host, port, socket.AF_UNSPEC,
                                socket.SOCK_STREAM, 0, socket.AI_PASSIVE):
        af, socktype, proto, canonname, sa = r
        try:
            s = socket.socket(af, socktype, proto)
        except socket.error, msg:
            s = None
            continue
        try:
            s.bind(sa)
            s.listen(1)
        except socket.error, msg:
            s.close()
            s = None
            continue
        break
    if s is None:
        print 'could not open socket'
        sys.exit(1)
    return s
Run Code Online (Sandbox Code Playgroud)

主机为无,端口为15000.

然后程序将接受连接,但仅接受来自同一台机器上的连接.我需要做些什么来接受来自互联网的连接?

Ikk*_*kke 8

试试0.0.0.0.这是最常用的.


msw*_*msw 5

第一个问题是你的除外块是吞咽错误,没有报告.第二个问题是您尝试绑定到特定接口,而不是INADDR_ANY.您可能绑定到"localhost",它只接受来自本地计算机的连接.

INADDR_ANY也称为常量0x00000000,但宏更有意义.

假设您正在使用IPv4(即"常规互联网"),请从套接字模块页面上的第一个示例中复制套接字/绑定代码.