1 unstable release

0.1.0 Dec 11, 2023

#25 in #socks5

Download history 30/week @ 2024-07-19 23/week @ 2024-07-26 18/week @ 2024-08-02 13/week @ 2024-08-09 14/week @ 2024-08-16 25/week @ 2024-08-23 56/week @ 2024-08-30 25/week @ 2024-09-06 29/week @ 2024-09-13 39/week @ 2024-09-20 32/week @ 2024-09-27 17/week @ 2024-10-04 26/week @ 2024-10-11 21/week @ 2024-10-18 15/week @ 2024-10-25 40/week @ 2024-11-01

104 downloads per month
Used in 5 crates (via sidevm-host-runtime)

Apache-2.0

11KB
174 lines

tokio-proxy

This simple lib helps to do tokio tcp connect via proxy (currently only socks5 is supported).

The connect function is similar to TcpStream::connect, with an extra argument to specify proxy url string.

pub async fn connect<A: ToSocketAddrsExt, T: AsRef<str>>(
    addr: A,
    proxy_url: T,
) -> io::Result<TcpStream>

example

You could check in examples/env_proxy.rs.

It checks env var all_proxy as proxy url, if non-exist, connect directly to httpbin.org.

    rt.block_on(async move {
        let mut s = match env::var("all_proxy") {
            Ok(proxy) => tokio_proxy::connect("httpbin.org:80", proxy).await.unwrap(),
            Err(_) => TcpStream::connect("httpbin.org:80").await.unwrap(),
        };

        s.write_all(
            b"GET /get HTTP/1.1\r\n\
        Host: httpbin.org\r\n\r\n",
        )
        .await
        .unwrap();

        let mut buf = [0; 512];
        s.read(&mut buf).await.unwrap();

        for line in str::from_utf8(&buf).unwrap().lines() {
            println!("{}", line);
        }
    });

If the proxy url uses socks5 scheme, then it would resolve the domain name locally and iterate all resolved ip addresses towards proxy, until one succeed or all failed.

If the proxy url uses socks5h scheme, then it would send the domain name directly to proxy.

It's just like what curl does.

$ all_proxy=socks5h://localhost:8080 cargo run --example env_proxy
    Finished dev [unoptimized + debuginfo] target(s) in 0.24s
     Running `target\debug\examples\env_proxy.exe`
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
...

Dependencies

~5–11MB
~116K SLoC