Last modified: Jun 03, 2025 By Alexander Williams

Install and Use PySocks for Proxy Support

PySocks is a Python library for proxy support. It allows you to route network traffic through SOCKS or HTTP proxies. This guide will show you how to install and use it.

What Is PySocks?

PySocks simplifies proxy usage in Python. It wraps the SOCKS4, SOCKS5, and HTTP proxy protocols. This makes it easy to integrate proxy support into your applications.

Install PySocks

You can install PySocks using pip. Run the following command in your terminal or command prompt.


pip install PySocks

If you need help with pip, check our guide on how to install pytz in Python easily for similar steps.

Basic Usage of PySocks

After installation, import the library in your Python script. Use the set_default_proxy function to configure the proxy.


import socks
import socket

# Set default proxy
socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket

# Test connection
try:
    print(socket.gethostbyname("example.com"))
except Exception as e:
    print("Error:", e)

This code routes all socket traffic through a SOCKS5 proxy. Replace the IP and port with your proxy details.

Advanced Proxy Configuration

PySocks supports authentication for proxies. Use the set_default_proxy function with username and password.


socks.set_default_proxy(
    socks.SOCKS5,
    "127.0.0.1",
    9050,
    username="user",
    password="pass"
)

This ensures secure proxy connections. For more on secure setups, see our Flask-Login installation guide.

Using PySocks with Requests

You can combine PySocks with the Requests library. First, install Requests if you haven't already.


pip install requests

Then, configure Requests to use the proxy.


import requests

proxies = {
    'http': 'socks5://user:pass@127.0.0.1:9050',
    'https': 'socks5://user:pass@127.0.0.1:9050'
}

response = requests.get("http://example.com", proxies=proxies)
print(response.text)

This sends HTTP requests through the proxy. It's useful for web scraping or API calls.

Error Handling

Always handle proxy connection errors. Use try-except blocks to manage failures gracefully.


try:
    socks.set_default_proxy(socks.SOCKS5, "invalid_ip", 9050)
    socket.socket = socks.socksocket
    print(socket.gethostbyname("example.com"))
except socks.ProxyConnectionError as e:
    print("Proxy error:", e)

This prevents crashes if the proxy is unreachable. For more on testing, see Pytest-mock installation.

Conclusion

PySocks is a powerful tool for proxy support in Python. It works with SOCKS and HTTP proxies. Follow this guide to integrate it into your projects.

Remember to handle errors and secure your connections. For more Python guides, explore our other tutorials.