Skip to content

Instantly share code, notes, and snippets.

@luftreich
Forked from mike-zhang/netfwd.go
Created December 16, 2016 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luftreich/272b37368aa1a60eac8adfbf80cfa3e1 to your computer and use it in GitHub Desktop.
Save luftreich/272b37368aa1a60eac8adfbf80cfa3e1 to your computer and use it in GitHub Desktop.
Simple GO TCP proxy
// can be run in go 1.0.3
// build : go build netfwd.go
package main
import (
"net"
"fmt"
"io"
"os"
)
func main() {
if len(os.Args) != 3 {
fatal("usage: netfwd localIp:localPort remoteIp:remotePort")
}
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment