Requests Integration Guide
This guide demonstrates how to configure, run, and test a v2socks proxy instance utilizing all public methods and properties, paired with the Python requests library.
Complete Integration Example
Below is a complete, commented Python script showing how to start the client, measure connection delay, export configurations, route traffic, and handle all library exceptions.
import requests
from v2socks import (
V2Socks,
V2SocksError,
ParseError,
CoreNotFoundError,
DownloadError,
ConnectionError
)
# Replace with your actual V2Ray config link (VLESS / VMess / Trojan)
CONFIG_LINK = "your-v2ray-config-link-here"
def run_proxy_test():
try:
# 1. Initialize and start the SOCKS5 proxy client using the context manager
# (It automatically downloads the stable Xray core on the first run)
with V2Socks(CONFIG_LINK, verbose=True) as proxy:
# 2. Get local proxy port and host address
proxy_port = proxy.port()
proxy_host = proxy.host
print(f"Proxy is running locally on: {proxy_host}:{proxy_port}")
# 3. Retrieve and print the complete SOCKS5 connection URL
proxy_url = proxy.socks_url
print(f"SOCKS5 proxy URL: {proxy_url}")
# 4. Measure connection delay to a target host in milliseconds
try:
latency = proxy.delay("https://www.google.com", timeout=5.0)
print(f"Connection latency: {latency:.2f} ms")
except ConnectionError as conn_err:
print(f"Latency measurement failed: {conn_err}")
# 5. Export and print the generated Xray JSON configuration as a dict
config_dict = proxy.export_config()
print("Generated Xray config outbound protocol:", config_dict["outbounds"][0]["protocol"])
# 6. Configure requests proxies dictionary to use the SOCKS5 proxy
# We use 'socks5h' scheme to ensure DNS resolution happens on the proxy side
proxies = {
"http": f"socks5h://{proxy_host}:{proxy_port}",
"https": f"socks5h://{proxy_host}:{proxy_port}"
}
# 7. Make a secure HTTP request through the proxy to fetch IP info
print("Fetching public IP address via proxy...")
response = requests.get("http://ip-api.com/json", proxies=proxies, timeout=10.0)
response.raise_for_status()
# 8. Parse and display the response data
data = response.json()
print("\n--- Connection Success ---")
print(f"Proxy Public IP: {data.get('query')}")
print(f"Country Location: {data.get('country')} ({data.get('countryCode')})")
print(f"ISP Provider: {data.get('isp')}")
print("--------------------------")
# Handle specialized library exceptions
except ParseError as e:
print(f"Parsing error (invalid config link): {e}")
except CoreNotFoundError as e:
print(f"Xray core binary error: {e}")
except DownloadError as e:
print(f"Failed to download Xray core: {e}")
except ConnectionError as e:
print(f"Proxy connection test failed: {e}")
except V2SocksError as e:
print(f"General v2socks library error: {e}")
except Exception as e:
print(f"An unexpected error occurred: {e}")
if __name__ == "__main__":
run_proxy_test()