Skip to content

Instantly share code, notes, and snippets.

@bitkevin
Created September 2, 2012 14:03
Show Gist options
  • Save bitkevin/3599217 to your computer and use it in GitHub Desktop.
Save bitkevin/3599217 to your computer and use it in GitHub Desktop.
tcp forword
package main
import (
"flag"
"fmt"
"io"
"log"
"net"
"os"
"time"
)
func main() {
var localAddrStr *string = flag.String("l", ":7071",
"listen address. ':7971' will listen all ip")
var remoteAddrStr *string = flag.String("r", "localhost:7070", "remote address")
isPrintHelp := flag.Bool("h", false, "show usage info")
flag.Parse()
if *isPrintHelp {
fmt.Printf("Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
os.Exit(1)
}
localTCPAddr, err := net.ResolveTCPAddr("tcp", *localAddrStr)
if localTCPAddr == nil {
log.Fatalf("net.ResolveTCPAddr failed: %s", err)
}
localListerner, err := net.ListenTCP("tcp", localTCPAddr)
if localListerner == nil {
log.Fatalf("portforward: %s", err)
}
log.Printf("forword tcp connections from: '%s', to: '%s'",
*localAddrStr, *remoteAddrStr)
for {
conn, err := localListerner.Accept()
if conn == nil {
log.Printf("accept failed: %s", err)
time.Sleep(1)
continue
}
go forward(conn, *remoteAddrStr)
}
}
func forward(localConn net.Conn, remoteAddrStr string) {
remoteConn, err := net.Dial("tcp", remoteAddrStr)
if remoteConn == nil {
log.Printf("remote dial failed: %s\n", err)
localConn.Close()
return
}
go func() {
defer localConn.Close()
io.Copy(localConn, remoteConn)
}()
go func() {
defer remoteConn.Close()
io.Copy(remoteConn, localConn)
}()
log.Printf("forward %s to %s", localConn.RemoteAddr(), remoteAddrStr)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment