Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple GO TCP proxy
package main
import (
"net"
"fmt"
"io"
"os"
)
func main() {
if len(os.Args) != 3 {
fatal("usage: netfwd local remote")
}
localAddr := os.Args[1]
remoteAddr := os.Args[2]
local, err := net.Listen("tcp", localAddr)
if local == nil {
fatal("cannot listen: %v", err)
}
for {
conn, err := local.Accept()
if conn == nil {
fatal("accept failed: %v", err)
}
go forward(conn, remoteAddr)
}
}
func forward(local net.Conn, remoteAddr string) {
remote, err := net.Dial("tcp", "", remoteAddr)
if remote == nil {
fmt.Fprintf(os.Stderr, "remote dial failed: %v\n", err)
return
}
go io.Copy(local, remote)
go io.Copy(remote, local)
}
func fatal(s string, a ... interface{}) {
fmt.Fprintf(os.Stderr, "netfwd: %s\n", fmt.Sprintf(s, a))
os.Exit(2)
}
@cloudaice

This comment has been minimized.

Copy link

cloudaice commented Feb 10, 2014

perfect ✌️

@fly2best

This comment has been minimized.

Copy link

fly2best commented Jan 24, 2015

awesome

@YihaoPeng

This comment has been minimized.

Copy link

YihaoPeng commented Oct 31, 2017

a small change, local and remote will Close() at the same time if one part disconnected.

package main
import (
        "net"
        "fmt"
        "io"
        "os"
)
func main() {
        if len(os.Args) != 3 {
                fatal("usage: netfwd local remote")
        }
        localAddr := os.Args[1]
        remoteAddr := os.Args[2]
        local, err := net.Listen("tcp", localAddr)
        if local == nil {
                fatal("cannot listen: %v", err)
        }
        for {
                conn, err := local.Accept()
                if conn == nil {
                        fatal("accept failed: %v", err)
                }
                go forward(conn, remoteAddr)
        }
}

func forward(local net.Conn, remoteAddr string) {
        remote, err := net.Dial("tcp", remoteAddr)
        if remote == nil {
                fmt.Fprintf(os.Stderr, "remote dial failed: %v\n", err)
                return
        }

        go func() {
            io.Copy(local, remote)
            local.Close()
            remote.Close()
        }()

        go func() {
            io.Copy(remote, local)
            remote.Close()
            local.Close()
        }()
}

func fatal(s string, a ... interface{}) {
        fmt.Fprintf(os.Stderr, "netfwd: %s\n", fmt.Sprintf(s, a))
        os.Exit(2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.