[英]Python error with HTTPserver
Hello I have the following code: 您好,我有以下代码:
import os, sys
from http.server import HTTPServer, CGIHTTPRequestHandler
webdir = '.'
port = 80
if len(sys.argv) > 1: webdir = sys.argv[1]
if len(sys.argv) > 2: port = int(sys.argv[2])
print("webdir '%s', port %s" % (webdir, port))
os.chdir(webdir)
svraddr = (" ", port)
srvrobj = HTTPServer(svraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever()
However, if I run this code with Administrator privileges, it returns an error: 但是,如果我以管理员权限运行此代码,它将返回错误:
Traceback (most recent call last):
File "C:\Users\Nitro\Desktop\web server\webserver.py", line 12, in <module>
srvrobj = HTTPServer(svraddr, CGIHTTPRequestHandler)
File "C:\Python33\lib\socketserver.py", line 430, in __init__
self.server_bind()
File "C:\Python33\lib\http\server.py", line 135, in server_bind
socketserver.TCPServer.server_bind(self)
File "C:\Python33\lib\socketserver.py", line 441, in server_bind
self.socket.bind(self.server_address)
socket.gaierror: [Errno 11004] getaddrinfo failed
What's wrong? 怎么了?
Try changing: 尝试更改:
svraddr = (" ", port)
To: 至:
svraddr = ("", port)
For me, changing this line: 对我来说,更改此行:
svraddr = (" ", port)
to: 至:
svraddr = ("", port)
will solve your problem. 将解决您的问题。 The string here (
" "
) represents what interface the socket should "bind" to: it should be the IP address matching an interface on your machine, but if it isn't, it seems Python will try to look it up (resolve it). 这里的字符串(
" "
)表示套接字应“绑定”到哪个接口:它应该是与您计算机上的接口匹配的IP地址,但是如果不是,则Python似乎会尝试查找(解决该问题) )。 " "
doesn't resolve. " "
无法解决。 ''
means "all interfaces": ''
表示“所有接口”:
For IPv4 addresses, two special forms are accepted instead of a host address: the empty string represents
INADDR_ANY
对于IPv4地址,接受两种特殊形式而不是主机地址:空字符串表示
INADDR_ANY
INADDR_ANY
is 0.0.0.0
, so a more explicit way of saying this is: INADDR_ANY
是0.0.0.0
,因此更明确的说法是:
svraddr = ('0.0.0.0', port)
"0.0.0.0" means "all interfaces". “ 0.0.0.0”表示“所有接口”。 Your webserver listens on the interfaces (roughly, network cards) that your socket is bound to, in this case, all of them.
您的Web服务器侦听套接字绑定到的接口(大概是网卡),在这种情况下,都是所有接口。 Often, it's useful to only bind to a particular interface (if you have more than one);
通常,仅绑定到特定接口(如果您有多个接口)很有用; also there's the loopback interface, which makes it such that only your machine can connect to the webserver:
还有一个环回接口,它使只有您的机器才能连接到网络服务器:
svraddr = ('127.0.0.1', port)
(or, alternatively, using the name lookup abilities that were tripping us up earlier) (或者,或者使用先前使我们绊倒的名称查找功能)
svraddr = ('localhost', port)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.