Sep 20, 12:00pm

To make Python's requests library use the IPv4 address of a target server via a SOCKS proxy created with ssh -D, you need to:

  1. Set up the SOCKS proxy using ssh -D.
  2. Configure requests to route traffic through that SOCKS proxy.
  3. Ensure the SOCKS proxy resolves hostnames to IPv4 (not IPv6) if needed.

🔧 Step 1: Create the SOCKS Proxy with ssh -D

On your local machine, run:

bash
ssh -D 1080 user@target-server
  • -D 1080: Creates a SOCKS proxy on port 1080 on your local machine.
  • user@target-server: The SSH user and target server (Debian 13) you want to route traffic through.

⚠️ This SOCKS proxy runs on your local machine, not the target server. The traffic will be tunneled through the SSH connection to the target server.


🐍 Step 2: Use the SOCKS Proxy in Python requests

The requests library does not natively support SOCKS. You need to use the requests[socks] package.

Install requests[socks]

bash
pip install requests[socks]

Example Python Code

python
import requests

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

response = requests.get('https://example.com', proxies=proxies)
print(response.text)
  • socks5h://: The h means the proxy will resolve hostnames (DNS) on the proxy side (i.e., on your local machine, but through the SSH tunnel).
  • 127.0.0.1:1080: The local SOCKS proxy created by ssh -D.

🌐 Step 3: Force IPv4 on the Target Server (Optional)

If the target server has both IPv4 and IPv6, and you want to ensure the target server uses IPv4 for outgoing connections:

On the target server, run:

bash
sudo sysctl -w net.ipv6.conf.all.disable_ipv6=1
sudo sysctl -w net.ipv6.conf.default.disable_ipv6=1

This disables IPv6 system-wide on the target server, forcing all outgoing connections to use IPv4.

⚠️ This affects the entire system. Use only if you control the target server and want to enforce IPv4.


🔍 Verify It Works

  1. Check your public IP from the target server's perspective:
    python
    import requests
    
    proxies = {
        'http': 'socks5h://127.0.0.1:1080',
        'https': 'socks5h://127.0.0.1:1080'
    }
    
    response = requests.get('https://api.ipify.org?format=json', proxies=proxies)
    print(response.json())
    • This should return the public IPv4 address of the target server.

✅ Summary

1
ssh -D 1080 user@target-server
2
pip install requests[socks]
3
Use proxies={'http': 'socks5h://127.0.0.1:1080', 'https': 'socks5h://127.0.0.1:1080'} in requests
4 (Optional)
Disable IPv6 on the target server if you want to force IPv4
Sep 20, 12:00pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more