Skip to main content

LinkSocks Python Bindings

PyPI version Python versions License: MIT

Python bindings for LinkSocks - a SOCKS5 over WebSocket proxy tool.

Overview

LinkSocks is a SOCKS proxy implementation over WebSocket protocol that allows you to securely expose SOCKS proxy services under Web Application Firewall (WAF) protection. This package provides Python bindings for the Go implementation.

Key Features

  • 🔄 Forward & Reverse Proxy: Support both forward and reverse SOCKS5 proxy modes
  • 🌐 WebSocket Transport: Works under WAF protection using standard WebSocket connections
  • ⚖️ Load Balancing: Round-robin load balancing for reverse proxy with multiple clients
  • 🔐 Authentication: SOCKS5 proxy authentication and secure token-based WebSocket authentication
  • 🌍 Protocol Support: Full IPv6 over SOCKS5 and UDP over SOCKS5 support
  • 🐍 Pythonic API: Both synchronous and asynchronous APIs with context manager support

Installation

pip install linksocks

Development Installation

git clone https://github.com/linksocks/linksocks.git
cd linksocks/_bindings/python
pip install -e .

Requirements

  • Python 3.8 or later
  • Go 1.19 or later (for building from source)

Quick Start

Forward Proxy Example

import asyncio
from linksocks import Server, Client

async def main():
    # Create server and client with async context managers
    async with Server(ws_port=8765) as server:
        # Add forward token asynchronously
        token = await server.async_add_forward_token()
        
        async with Client(token, ws_url="ws://localhost:8765", socks_port=9870, no_env_proxy=True) as client:
            print("✅ Forward proxy ready!")
            print("🌐 SOCKS5 proxy: 127.0.0.1:9870")
            print("🔧 Test: curl --socks5 127.0.0.1:9870 http://httpbin.org/ip")
            
            # Keep running
            await asyncio.sleep(3600)

if __name__ == "__main__":
    asyncio.run(main())

Reverse Proxy Example

import asyncio
from linksocks import Server, Client

async def main():
    # Create server and client with async context managers
    async with Server(ws_port=8765) as server:
        # Add reverse token (port is auto-allocated)
        result = server.add_reverse_token()
        print(f"🔑 Reverse token: {result.token}")
        print(f"🌐 SOCKS5 proxy will be available on: 127.0.0.1:{result.port}")
        
        # Create client in reverse mode
        async with Client(result.token, ws_url="ws://localhost:8765", reverse=True, no_env_proxy=True) as client:
            print("✅ Reverse proxy ready!")
            print(f"🔧 Test: curl --socks5 127.0.0.1:{result.port} http://httpbin.org/ip")
            
            # Keep running
            await asyncio.sleep(3600)

if __name__ == "__main__":
    asyncio.run(main())

Web Site Example

The Web class publishes a local HTTP(S) site through a linksocks.js relay. Requests reuse the WebSocket tunnel, so the origin does not need a public IP or an inbound port.

from linksocks import Web

with Web(
    ["http://127.0.0.1:8080"],
    url="wss://l.zetx.tech",
) as site:
    host = site.wait_ready(timeout=30)
    print(f"Published at https://{host}")

Use token="..." for a dashboard token, domain="blog.example.com" for a fixed hostname, and pass several backend URLs to balance across local origins. insecure=True skips TLS verification for HTTPS backends.

The same provider is available from the installed CLI:

$ linksocks web -u wss://l.zetx.tech -l http://127.0.0.1:8080
[11/02 16:42] INFO     Welcome to LinkSocks.js relay server. This server is running in edge: AMS
                       (Amsterdam, Netherlands), relay: HKG (Hong Kong). Your connection comes from CN
                       (<client-ip>). After you connected, this relay group has 1 provider and 0
                       connectors.
Web site published: https://gden3eme.team1.cc.cd
              INFO     Web site published backends=1 expires=2026-11-02T22:42:28+08:00
                       host=gden3eme.team1.cc.cd temporary=True url=https://gden3eme.team1.cc.cd
              INFO     Temporary URL https://gden3eme.team1.cc.cd expires at 2026-11-02T22:42:28+08:00; it
                       will rotate automatically

The relay forwards requests to the local origin:

$ curl -sS https://gden3eme.team1.cc.cd/
<!doctype html>
<html><head><title>LinkSocks demo site</title></head>
<body><h1>Hello from a local origin</h1><p id="marker">linksocks-web-demo-20261102</p><script src="/assets/app.js"></script></body></html>

$ curl -sS -o /dev/null -w '%{http_code}\n' https://gden3eme.team1.cc.cd/assets/app.js
200

API Reference

Web Class

The Web class publishes local HTTP(S) backends through a linksocks.js relay.

from linksocks import Web

site = Web(
    ["http://127.0.0.1:8080"],
    url="wss://l.zetx.tech",
    token="",
    domain=None,
    insecure=False,
    no_reconnect=False,
    reconnect_delay=None,
    logger=None,
)
Parameter Type Default Description
backends list[str] Required Local HTTP(S) origin URLs
url str "ws://localhost:8765" linksocks.js server URL
token str "" Dashboard provider token
domain str | None None Fixed hostname under the relay's WEB_ZONE
insecure bool False Skip TLS verification for HTTPS backends
no_reconnect bool False Stop when the relay disconnects
reconnect_delay DurationLike None Delay between reconnect attempts
logger logging.Logger None Python logger for relay messages

Methods:

  • wait_ready(timeout=None) / async_wait_ready(timeout=None) — block until registration and return the assigned hostname.
  • host — current hostname, updated when a temporary URL rotates.
  • close() / async_close() — stop the provider and release the relay registration.
  • Web supports both with and async with; the async context manager waits for registration before entering the block.

Server Class

The Server class manages WebSocket connections and provides SOCKS5 proxy functionality.

from linksocks import Server, AccessRule

# Create server with options
server = Server(
    ws_host="0.0.0.0",           # WebSocket listen address
    ws_port=8765,                # WebSocket listen port  
    socks_host="127.0.0.1",      # SOCKS5 listen address (reverse mode)
    buffer_size=32768,           # Buffer size for data transfer
    api_key="your_api_key",      # Enable HTTP API
    channel_timeout=30.0,        # WebSocket channel timeout (seconds)
    connect_timeout=10.0,        # Connection timeout (seconds)
    connector_wait_provider=5.0, # Connector wait for provider reconnect (seconds)
    fast_open=False,             # Enable fast open optimization
    upstream_proxy="socks5://proxy:1080",  # Upstream proxy
    upstream_username="user",    # Upstream proxy username
    upstream_password="pass",    # Upstream proxy password
    entry_access_control=[AccessRule(addrs=["192.168.1.0/24"], ports=[22, (90, 150)])],
    dial_access_control=[AccessRule(addrs=["10.0.0.0/8"], ports=[(8000, 9000)])],
)

Token Management

# Add forward proxy token (synchronous)
token = server.add_forward_token("custom_token")  # or auto-generate with None

# Add forward proxy token (asynchronous - recommended)
token = await server.async_add_forward_token("custom_token")

# Add reverse proxy token
result = server.add_reverse_token(
    token="custom_token",        # optional, auto-generated if None
    port=9870,                   # optional, auto-allocated if None
    username="socks_user",       # optional, SOCKS5 auth username
    password="socks_pass",       # optional, SOCKS5 auth password
    allow_manage_connector=True, # optional, allow client connector management
    rules=[AccessRule(addrs=["192.168.1.1-255"], ports=[80])],  # optional, per-token access control
)
print(f"Token: {result.token}, Port: {result.port}")

# Add connector token  
connector_token = server.add_connector_token("connector_token", "reverse_token")

# Remove any token
success = server.remove_token("token_to_remove")

Running the Server

# Asynchronous (recommended) - automatically waits for ready
async with server:
    print("Server is ready!")  # No need for async_wait_ready()
    # Server runs while in context

# Synchronous - requires manual wait
server.wait_ready()  # Blocks until ready
# Server runs in background
server.close()  # Clean shutdown

# Manual wait with timeout (only needed for synchronous usage)
server.wait_ready(timeout=30.0)  # 30 second timeout
await server.async_wait_ready(timeout="30s")  # Go duration string (rarely needed)

Client Class

The Client class connects to WebSocket servers and provides SOCKS5 functionality.

from linksocks import Client, AccessRule

# Create client with options
client = Client(
    token="your_token",          # Authentication token (required)
    ws_url="ws://localhost:8765", # WebSocket server URL
    reverse=False,               # Enable reverse proxy mode
    socks_host="127.0.0.1",      # SOCKS5 listen address (forward mode)
    socks_port=9870,             # SOCKS5 listen port (forward mode)
    socks_username="user",       # SOCKS5 auth username
    socks_password="pass",       # SOCKS5 auth password
    socks_wait_server=True,      # Wait for server before starting SOCKS5
    reconnect=True,              # Auto-reconnect on disconnect
    reconnect_delay=5.0,         # Reconnect delay (seconds)
    buffer_size=32768,           # Buffer size for data transfer
    channel_timeout=30.0,        # WebSocket channel timeout
    connect_timeout=10.0,        # Connection timeout
    threads=4,                   # Number of processing threads
    fast_open=False,             # Enable fast open optimization
    upstream_proxy="socks5://proxy:1080",  # Upstream proxy
    upstream_username="proxy_user",        # Upstream proxy username
    upstream_password="proxy_pass",        # Upstream proxy password
    no_env_proxy=False,          # Ignore proxy environment variables
    entry_access_control=[AccessRule(addrs=["192.168.1.0/24"], ports=[22])],
    dial_access_control=[AccessRule(addrs=["0.0.0.0/0"], ports=[443])],
)

Running the Client

# Asynchronous (recommended) - automatically waits for ready
async with client:
    print(f"Client ready! SOCKS5 port: {client.socks_port}")
    print(f"Connected: {client.is_connected}")
    # Client runs while in context

# Synchronous - requires manual wait
client.wait_ready()
print(f"Connected: {client.is_connected}")
client.close()  # Clean shutdown

Connector Management (Reverse Mode)

# Add connector token (reverse mode only)
connector_token = client.add_connector("my_connector")  # or auto-generate
connector_token = await client.async_add_connector(None)  # async version

Logging

import logging
from linksocks import set_log_level

# Set global log level
set_log_level(logging.DEBUG)
set_log_level("INFO")  # String format

# Use custom logger
logger = logging.getLogger("my_app")
logger.setLevel(logging.DEBUG)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
logger.addHandler(handler)

server = Server(logger=logger)
client = Client("token", logger=logger)

Access Control

Server, Client and reverse tokens accept AccessRule objects that restrict which destinations can be reached. Each rule pairs an address range with a port range; rules are OR-ed together, and within a rule the address must match and the port must match. Empty rules allow everything.

from linksocks import AccessRule, Server

rules = [
    AccessRule(addrs=["192.168.1.0/24", "192.168.1.1-255"], ports=[22, (90, 150)]),
    AccessRule(addrs=["10.0.0.0/8"], ports=[443]),
]

server = Server(entry_access_control=rules, dial_access_control=rules)
  • addrs: CIDR blocks (192.168.1.0/24), bare IPs (192.168.1.1), or address ranges (1.1.1.1-255 for 1.1.1.1-1.1.1.255, 1.1.1.1-2.2.2.255 for 1.1.1.1-2.2.2.255)
  • ports: single numbers (22) or inclusive (start, end) tuples ((90, 150))

Entry control (entry_access_control) restricts what the local SOCKS entry accepts; dial control (dial_access_control) restricts the destinations actually dialed outbound. On the server side, per-token rules override the server-level entry control for that token.

Advanced Examples

Relay Proxy with Connector Management

import asyncio
from linksocks import Server, Client

async def agent_proxy():
    # Server with connector autonomy enabled
    async with Server(ws_port=8765) as server:
        result = server.add_reverse_token(allow_manage_connector=True)
        print(f"🔑 Provider token: {result.token}")
        print(f"🌐 SOCKS5 proxy will be available on: 127.0.0.1:{result.port}")
        
        # Provider client (provides network access)
        async with Client(result.token, ws_url="ws://localhost:8765", reverse=True, no_env_proxy=True) as provider:
            print("✅ Agent proxy server and provider ready!")
            
            # Provider can manage its own connectors
            connector_token = await provider.async_add_connector("my_connector")
            print(f"🔑 Connector token: {connector_token}")
            
            # Now external connectors can use this token
            print(f"🔧 Start connector: linksocks connector -t {connector_token} -u ws://localhost:8765 -p 1180")
            
            await asyncio.sleep(3600)

asyncio.run(agent_proxy())

Error Handling and Monitoring

import asyncio
import logging
from linksocks import Client

async def robust_client():
    logger = logging.getLogger("robust_client")
    
    client = Client(
        "your_token",
        ws_url="ws://server:8765",
        reconnect=True,
        reconnect_delay=5.0,
        no_env_proxy=True,
        logger=logger
    )
    
    try:
        async with client:
            logger.info("✅ Client connected successfully")
            
            # Monitor connection status
            while True:
                if not client.is_connected:
                    logger.warning("⚠️  Connection lost, reconnecting...")
                    
                await asyncio.sleep(5)
                    
    except asyncio.TimeoutError:
        logger.error("❌ Connection timeout after 30 seconds")
    except Exception as e:
        logger.error(f"❌ Client error: {e}")
    finally:
        logger.info("🔄 Client shutting down")

asyncio.run(robust_client())

HTTP API Integration

import asyncio
import aiohttp
from linksocks import Server

async def api_server_example():
    # Start server with API enabled
    server = Server(ws_port=8765, api_key="secret_api_key")
    
    async with server:
        print("✅ Server with API ready!")
        
        # Use HTTP API to manage tokens
        async with aiohttp.ClientSession() as session:
            headers = {"X-API-Key": "secret_api_key"}
            
            # Add forward token via API
            async with session.post(
                "http://localhost:8765/api/token",
                headers=headers,
                json={"type": "forward", "token": "api_token"}
            ) as resp:
                result = await resp.json()
                print(f"📝 Added token via API: {result}")
            
            # Get server status
            async with session.get(
                "http://localhost:8765/api/status",
                headers=headers
            ) as resp:
                status = await resp.json()
                print(f"📊 Server status: {status}")
        
        await asyncio.sleep(3600)

asyncio.run(api_server_example())

Type Hints

The package includes comprehensive type hints for better IDE support:

from typing import Optional
from linksocks import Server, Client, ReverseTokenResult

def create_proxy_pair(token: str, port: Optional[int] = None) -> tuple[Server, Client]:
    server = Server(ws_port=8765)
    server.add_forward_token(token)
    
    client = Client(token, ws_url="ws://localhost:8765", socks_port=port or 9870, no_env_proxy=True)
    return server, client

# ReverseTokenResult is a dataclass
server = Server(ws_port=8765)
result: ReverseTokenResult = server.add_reverse_token()
print(f"Token: {result.token}, Port: {result.port}")

Comparison with CLI Tool

Feature Python Bindings Go CLI Tool
Integration Library for Python apps Standalone binary
API Style Object-oriented, async/sync Command-line flags
Use Cases Embedded in applications Quick setup, scripting
Performance Same (uses Go backend) Same
Features Full feature parity Full feature parity

Troubleshooting

Common Issues

  1. Import Error: Make sure Go 1.19+ is installed when building from source
  2. Connection Refused: Check that server is running and ports are correct
  3. Authentication Failed: Verify tokens match between server and client
  4. Port Already in Use: Choose different ports or check for existing processes

Debug Logging

import logging
from linksocks import set_log_level

# Enable debug logging
set_log_level(logging.DEBUG)

# Or use environment variable
import os
os.environ["LINKSOCKS_LOG_LEVEL"] = "DEBUG"

Performance Tuning

# Increase buffer size for high-throughput scenarios
server = Server(buffer_size=65536)
client = Client("token", buffer_size=65536, threads=8)

# Enable fast open for lower latency
server = Server(fast_open=True)
client = Client("token", fast_open=True)

Contributing

We welcome contributions! Please see the main LinkSocks repository for contribution guidelines.

License

This project is licensed under the MIT License.

Metadata

Release files for linksocks 1.14.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for linksocks 1.14.3
File Size Uploaded Provenance Actions
linksocks-1.14.3.tar.gz 275.3 kB With provenance Details for linksocks-1.14.3.tar.gz

Built distributions (wheels)

Table of built distributions (wheels) for linksocks 1.14.3
File Actions
linksocks-1.14.3-py3-none-win_amd64.whl Python 3 none Windows x86-64 Details for linksocks-1.14.3-py3-none-win_amd64.whl
linksocks-1.14.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl Python 3 none Linux glibc 2.17+ ARM64 Details for linksocks-1.14.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
linksocks-1.14.3-py3-none-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl Python 3 none Linux glibc 2.5+ x86-64, Linux glibc 2.17+ x86-64 Details for linksocks-1.14.3-py3-none-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl
linksocks-1.14.3-py3-none-macosx_15_0_universal2.whl Python 3 none macOS 15.0+ universal2 (ARM64, x86-64) Details for linksocks-1.14.3-py3-none-macosx_15_0_universal2.whl

Total release size: 28.3 MB

Release files / linksocks-1.14.3.tar.gz

Download URL linksocks-1.14.3.tar.gz
Size 275.3 kB
Tags Source
SHA-256 checksum
How to use checksums
9e87bf933e4bc2bcc6247f6064fa8b7d8c4f348b37c1a73ac9d1ee4a0946830a
BLAKE2b-256 checksum
How to use checksums
fc7ec1ff6462af05ab7e9df3b0b17c98f0df6c9af5830319a1b139a1d4d1829a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Release files / linksocks-1.14.3-py3-none-win_amd64.whl

Download URL linksocks-1.14.3-py3-none-win_amd64.whl
Size 8.1 MB
Tags Python 3 Windows x86-64
SHA-256 checksum
How to use checksums
d0527de385c95488360001257293ac47b3d9c2b2eeeff7bdf515cd1577b106fc
BLAKE2b-256 checksum
How to use checksums
72a9037a4ef4163ae0c8e51d49554174247d91b284cbbf1292615e271f0a593c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Release files / linksocks-1.14.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl

Download URL linksocks-1.14.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl
Size 7.5 MB
Tags Linux glibc 2.17+ ARM64 Python 3
SHA-256 checksum
How to use checksums
f64dbada3754250323ad10d821bcd2c6bd59e54f0f4e7e63b110ef73e4577eed
BLAKE2b-256 checksum
How to use checksums
15a2ed9fe4caa96d338a2d9a7f677c8984addd0a10d09b2bccb6b1e48d88df31
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Release files / linksocks-1.14.3-py3-none-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl

Download URL linksocks-1.14.3-py3-none-manylinux1_x86_64.manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_5_x86_64.whl
Size 8.2 MB
Tags Linux glibc 2.17+ x86-64 Linux glibc 2.5+ x86-64 Python 3
SHA-256 checksum
How to use checksums
d3bf6cbc8558b33f5332059ba12af33e4e661a24f7d65ee6b5dc73857187c9a8
BLAKE2b-256 checksum
How to use checksums
4744d40baae021a75321b490468911650a5cb0c400d6c2d965b6708afb1dc99e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Release files / linksocks-1.14.3-py3-none-macosx_15_0_universal2.whl

Download URL linksocks-1.14.3-py3-none-macosx_15_0_universal2.whl
Size 4.2 MB
Tags Python 3 macOS 15.0+ universal2 (ARM64, x86-64)
SHA-256 checksum
How to use checksums
aebe92b8dfd36a14048a82918ba2661170d700532d22cbb16e7aad0dd6a6d9e3
BLAKE2b-256 checksum
How to use checksums
a52dbf1a40995490698007975f6d2b5d03b6f1289cc0015372c4fba1c70dd696
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Security for linksocks 1.14.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

All 5 files in this release have been uploaded with provenance metadata.

Select from 5 files

Attestation for linksocks-1.14.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.14.3 This release

5 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page