简体   繁体   中英

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). " " 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

INADDR_ANY is 0.0.0.0 , so a more explicit way of saying this is:

svraddr = ('0.0.0.0', port)

"0.0.0.0" means "all interfaces". Your webserver listens on the interfaces (roughly, network cards) that your socket is bound to, in this case, all of them. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM