Python urllib2 无法通过非80端口打开localhost?错误10013

3 投票
1 回答
11809 浏览
提问于 2025-04-16 22:10

这是我的 server.py 文件:

import BaseHTTPServer
import SocketServer

class TestRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        self.wfile.write("hello world at %s" % __file__)

server = BaseHTTPServer.HTTPServer(('', 10000), TestRequestHandler)
#server = SocketServer.ThreadingTCPServer(('', 8888), TestRequestHandler)
server.serve_forever()

这是我的 client.py 文件:

import urllib2
req = urllib2.Request('http://127.0.0.1:10000/')
handle = urllib2.urlopen(req)
content = handle.read()

然后我启动了 server.py,运行正常。

当我启动 client.py 时,在 Windows 7, Python 2.6 上出现了这个错误:

Traceback (most recent call last):
  File "D:\Dropbox\Forge\urllib-error\client.py", line 3, in <module>
    handle = urllib2.urlopen(req)
  File "C:\Python26\lib\urllib2.py", line 126, in urlopen
    return _opener.open(url, data, timeout)
  File "C:\Python26\lib\urllib2.py", line 391, in open
    response = self._open(req, data)
  File "C:\Python26\lib\urllib2.py", line 409, in _open
    '_open', req)
  File "C:\Python26\lib\urllib2.py", line 369, in _call_chain
    result = func(*args)
  File "C:\Python26\lib\urllib2.py", line 1161, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "C:\Python26\lib\urllib2.py", line 1136, in do_open
    raise URLError(err)
urllib2.URLError: <urlopen error [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions>

当我在浏览器中打开 http://127.0.0.1:10000/ 时,一切正常。这说明服务器没问题。

当我在 client.py 中把 http://127.0.0.1:10000/ 替换成 http://127.0.0.1/http://127.0.0.1:80/ 时,一切都正常(这是另一个在80端口上运行的网络服务器 - apache)。

我哪里做错了?

更新:使用这个 client2.py 时也出现同样的错误:

import urllib2
handle = urllib2.urlopen('http://127.0.0.1:10000/')
content = handle.read()

更新:问题解决了。是我的防火墙问题。关闭后,一切正常。真是太傻了,谢谢你们的阅读 :-)

1 个回答

5

本地防火墙阻止了连接。当防火墙关闭时,一切都正常。

撰写回答