python 在python中制作UDP套接字时使用什么主机?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/868173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What host to use when making a UDP socket in python?
提问by c0m4
I want ro receive some data that is sent as a UDP packet over VPN. So wrote (mostly copied) this program in python:
我希望 ro 接收一些作为 UDP 数据包通过 VPN 发送的数据。所以在python中编写(主要是复制)这个程序:
import socket
import sys
HOST = ???????
PORT = 80
# SOCK_DGRAM is the socket type to use for UDP sockets
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((HOST,PORT))
data,addr = sock.recv(1024)
print "Received: %s" % data
print "Addr: %s" % addr
What should I use as host? I know the IP of the sender but it seems anything thats not local gives me socket.error: [Errno 10049]. The IP that the VPN gives me (the same IP that the sender sends to, that is)? Or just localhost?
我应该使用什么作为主机?我知道发件人的 IP,但似乎任何非本地的东西都会给我 socket.error: [Errno 10049]。VPN 给我的 IP(与发件人发送到的 IP 相同)?还是只是本地主机?
回答by Nick Johnson
The host argument is the host IP you want to bind to. Specify the IP of one of your interfaces (Eg, your public IP, or 127.0.0.1 for localhost), or use 0.0.0.0 to bind to all interfaces. If you bind to a specific interface, your service will only be available on that interface - for example, if you want to run something that can only be accessed via localhost, or if you have multiple IPs and need to run different servers on each.
host 参数是您要绑定到的主机 IP。指定您的接口之一的 IP(例如,您的公共 IP,或本地主机的 127.0.0.1),或使用 0.0.0.0 绑定到所有接口。如果您绑定到特定接口,您的服务将仅在该接口上可用 - 例如,如果您想运行只能通过 localhost 访问的内容,或者如果您有多个 IP 并且需要在每个 IP 上运行不同的服务器。
回答by gimel
"0.0.0.0" will listen for all incoming hosts. For example,
“0.0.0.0”将侦听所有传入主机。例如,
sock.bind(("0.0.0.0", 999))
data,addr = sock.recv(1024)
回答by Lance Richardson
Use:
利用:
sock.bind(("", 999))