Search code examples
gotcptor

TCP connection over Tor in Golang


Is it possible to initiate a TCP connection over the tor network in go? I've looked around but haven't found a mention of it.

If not, is there something similar to TCP - like websockets - that can be used instead?

Note: There's no source code for me to post at the moment since there isn't any yet. This is simply research beforehand.


Solution

  • A tor node acts as a SOCKS proxy on port 9050. Go support for the SOCKS5 protocol lives in package golang.org/x/net/proxy:

    import "golang.org/x/net/proxy"
    

    In order to make connections through tor, you first need to create a new Dialer that goes through the local SOCKS5 proxy:

    dialer, err := proxy.SOCKS5("tcp", "127.0.0.1:9050", nil, nil)
    if err != nil {
        log.Fatal(err)
    }
    

    To use this dialer, you just call dialer.Dial instead of net.Dial:

    conn, err := dialer.Dial("tcp", "stackoverflow.com:80")
    if err != nil {
        log.Fatal(err)
    }
    defer conn.Close()