Skip to content

Instantly share code, notes, and snippets.

@zupzup
Created March 20, 2017 10:03
Show Gist options
  • Save zupzup/14ea270252fbb24332c5e9ba978a8ade to your computer and use it in GitHub Desktop.
Save zupzup/14ea270252fbb24332c5e9ba978a8ade to your computer and use it in GitHub Desktop.
Go TCP Proxy / Port Forwarding Example (https://zupzup.org/go-port-forwarding/)
package main
import (
"flag"
"fmt"
"io"
"log"
"net"
"os"
"os/signal"
)
var (
target string
port int
)
func init() {
flag.StringVar(&target, "target", "", "the target (<host>:<port>)")
flag.IntVar(&port, "port", 7757, "the tunnelthing port")
}
func main() {
flag.Parse()
signals := make(chan os.Signal, 1)
stop := make(chan bool)
signal.Notify(signals, os.Interrupt)
go func() {
for _ = range signals {
fmt.Println("\nReceived an interrupt, stopping...")
stop <- true
}
}()
incoming, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
if err != nil {
log.Fatalf("could not start server on %d: %v", port, err)
}
fmt.Printf("server running on %d\n", port)
client, err := incoming.Accept()
if err != nil {
log.Fatal("could not accept client connection", err)
}
defer client.Close()
fmt.Printf("client '%v' connected!\n", client.RemoteAddr())
target, err := net.Dial("tcp", target)
if err != nil {
log.Fatal("could not connect to target", err)
}
defer target.Close()
fmt.Printf("connection to server %v established!\n", target.RemoteAddr())
go func() { io.Copy(target, client) }()
go func() { io.Copy(client, target) }()
<-stop
}
@zupzup
Copy link
Author

zupzup commented Nov 19, 2020

hey @phanirithvij!

This very simple example for a blog post shouldn't be used for any real application, it's use is to show off some concepts.

The reason it doesn't work well is because it only accepts one connection (incoming.Accept), whereas the example you posted accepts in a loop and hence handles multiple connections. That's also why some files go through, and others don't in your test.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment