无法通过python连接到TOR

时间:2015-02-09 02:21:58

标签: python tor

我正在尝试通过python连接到TOR,但它不会让我的代码是:

def tor_connection():
    socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True)
    socket.socket = socks.socksocket

def main():
    tor_connection()
    print('Connected to tor')
    con = httplib.HTTPConnection('myip.dnsomatic.com/')
    con.request('GET', '/')
    response = con.getresponse()
    print(response.read())

main()

即使它给我下一条错误消息:

Traceback (most recent call last):
  File "C:/Users/anon/PycharmProjects/Scraper/tor.py", line 198, in <module>
    main()
  File "C:/Users/anon/PycharmProjects/Scraper/tor.py", line 194, in main
    con.request('GET', '/')
  File "C:\Python27\lib\httplib.py", line 1001, in request
    self._send_request(method, url, body, headers)
  File "C:\Python27\lib\httplib.py", line 1035, in _send_request
    self.endheaders(body)
  File "C:\Python27\lib\httplib.py", line 997, in endheaders
    self._send_output(message_body)
  File "C:\Python27\lib\httplib.py", line 850, in _send_output
    self.send(msg)
  File "C:\Python27\lib\httplib.py", line 812, in send
    self.connect()
  File "C:\Python27\lib\httplib.py", line 793, in connect
    self.timeout, self.source_address)
  File "C:\Python27\lib\socket.py", line 553, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno 11001] getaddrinfo failed

我只是一个初学者,有人可以帮助我吗?我已经在另一台笔记本电脑上尝试了它,但它的错误消息相同

1 个答案:

答案 0 :(得分:0)

这不是socks的问题。您需要指定不带尾随/的主机名:

>>> # with /
>>> httplib.HTTPConnection('myip.dnsomatic.com/').request('GET', '/')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/httplib.py", line 973, in request
    self._send_request(method, url, body, headers)
  File "/usr/lib/python2.7/httplib.py", line 1007, in _send_request
    self.endheaders(body)
  File "/usr/lib/python2.7/httplib.py", line 969, in endheaders
    self._send_output(message_body)
  File "/usr/lib/python2.7/httplib.py", line 829, in _send_output
    self.send(msg)
  File "/usr/lib/python2.7/httplib.py", line 791, in send
    self.connect()
  File "/usr/lib/python2.7/httplib.py", line 772, in connect
    self.timeout, self.source_address)
  File "/usr/lib/python2.7/socket.py", line 553, in create_connection
    for res in getaddrinfo(host, port, 0, SOCK_STREAM):
socket.gaierror: [Errno -2] Name or service not known

>>> # without /
>>> httplib.HTTPConnection('myip.dnsomatic.com').request('GET', '/')
>>>