Python套接字绑定到任何IP?
我有一个小的单边消息发送器,当我在代码中指定要连接的 IP 时,它可以工作,但是,我在允许套接字接受来自任何 IP 的连接时遇到了麻烦。这是有问题的行。
mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
mySocket.bind ( ( '', 2727 ) )
''
用于本地主机,如果我手动输入 IP,它就可以工作,例如 '192.168.1.106'
,但是,我怎样才能让它对所有人开放呢?或者我为此使用了错误的连接类型?
I have a small one sided message sender that works while I specify the IP to connect to in code, however, I am having trouble allowing the socket to accept connections from any IP. Here is the line that is the problem.
mySocket = socket.socket ( socket.AF_INET, socket.SOCK_STREAM )
mySocket.bind ( ( '', 2727 ) )
The ''
is for localhost, and it works if I manually enter IP, eg '192.168.1.106'
, however, how can I leave it open to all? Or am I using the wrong connection type for this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想要绑定到所有可用的 IPv4 地址,请指定
0.0.0.0
作为您的 IP 地址。如果您位于路由器后面并且希望套接字可通过互联网访问,而不仅仅是在 LAN 上可用,则需要设置端口转发规则,以便 LAN 外部的用户可以访问该服务。有关
0.0.0.0
的详细信息,请参阅以下 ServerFault 问题:https:// serverfault.com/questions/78048/ip-address-0-0-0-0-and-127-0-0-1之间的差异是什么If you want to bind to all available IPv4 addresses, specify
0.0.0.0
as your IP address. If you're behind a router and wish to have your socket internet-accessible, rather than just available on your LAN, you'll need to set up a port forwarding rule so that users outside your LAN can access the service.See the following ServerFault question for more info on
0.0.0.0
: https://serverfault.com/questions/78048/whats-the-difference-between-ip-address-0-0-0-0-and-127-0-0-1绑定到
''
与'0.0.0.0'
具有相同的效果,可以更轻松地过渡到 IPv6。根据操作系统的不同,打开
socket.AF_INET6
套接字会侦听 IPv4 和 IPv6。Binding to
''
has the same effect as to'0.0.0.0'
makes the transition to IPv6 easier.Depending on the OS, opening a
socket.AF_INET6
socket listens to IPv4 and IPv6.绑定到 0.0.0.0 将允许它接受来自任何可以路由到它的 IPv4 地址的连接。
Binding to 0.0.0.0 will allow it to accept connections from any IPv4 address that can route to it.