11

Here is the code that i have till now

import socks
import socket
import requests
import json

socks.setdefaultproxy(proxy_type=socks.PROXY_TYPE_SOCKS5, addr="127.0.0.1", port=9050)
socket.socket = socks.socksocket

data = json.loads(requests.get("http://freegeoip.net/json/").text)

and it works fine. The problem is when i use a .onion url it shows error

Failed to establish a new connection: [Errno -2] Name or service not known

After researching a little i found that although the http request is made over tor the resolution still occours over clearnet. What is the proper way so i can also have the domain resolved over tor network to connect to .onion urls ?

georoot
  • 3,557
  • 1
  • 30
  • 59
  • You can't just connect over HTTP - Have you looked at the excellent Python [Stem package for Tor?](https://stem.torproject.org/) – samiles Apr 28 '17 at 14:48
  • @samiles let me have a look at that now :) – georoot Apr 28 '17 at 14:50
  • You can find a monkeypatch for urllib2 [here](http://stackoverflow.com/questions/5148589/python-urllib-over-tor?answertab=votes#tab-top) – t.m.adam Apr 28 '17 at 18:43

2 Answers2

12

Try to avoid the monkey patching if possible. If you're using modern version of requests, then you should have this functionality already.

import requests
import json

proxies = {
    'http': 'socks5h://127.0.0.1:9050',
    'https': 'socks5h://127.0.0.1:9050'
}

data = requests.get("http://altaddresswcxlld.onion",proxies=proxies).text

print(data)

It's important to specify the proxies using the socks5h:// scheme so that DNS resolution is handled over SOCKS so Tor can resolve the .onion address properly.

drew010
  • 68,777
  • 11
  • 134
  • 162
0

There is a more simple solution for this, but therefore you will need Kali Linux. If you have this OS, you can install tor service and kalitorify, start tor service with: sudo service tor start and start kalitorify with sudo kalitorify -t. Now your trafic will be send through tor and you can access .onion sites just as they would be normal sites.