Last active
March 18, 2025 15:06
-
-
Save keepitsimple/1de1306a396d5534d7f3302e606ba72a to your computer and use it in GitHub Desktop.
aiohttp + aiosocks: async tor proxy example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import aiohttp | |
import aiosocks | |
from aiosocks.connector import ProxyConnector, ProxyClientRequest | |
async def main(): | |
async with aiohttp.ClientSession() as session: | |
async with session.get('http://icanhazip.com/') as resp: | |
body = await resp.text() | |
host_ip = body.strip() | |
print('ip: {}'.format(host_ip)) | |
conn = ProxyConnector(remote_resolve=False) | |
try: | |
async with aiohttp.ClientSession(connector=conn, request_class=ProxyClientRequest) as session: | |
async with session.get('http://icanhazip.com/', proxy='socks5://127.0.0.1:9060') as resp: | |
body = await resp.text() | |
tor_ip = body.strip() | |
print('tor ip: {}'.format(tor_ip)) | |
except aiohttp.ClientProxyConnectionError: | |
# connection problem | |
pass | |
except aiohttp.ClientConnectorError: | |
# ssl error, certificate error, etc | |
pass | |
except aiosocks.SocksError: | |
# communication problem | |
pass | |
if __name__ == '__main__': | |
loop = asyncio.get_event_loop() | |
loop.run_until_complete(main()) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
why you have port 9060?