Created
March 20, 2017 10:03
-
-
Save zupzup/14ea270252fbb24332c5e9ba978a8ade to your computer and use it in GitHub Desktop.
Go TCP Proxy / Port Forwarding Example (https://zupzup.org/go-port-forwarding/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
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
Hi, great concept.
But I think it's very slow for http requests, or is it not meant for HTTP requests?
I was trying to access a nodejs application which serves on port 8080, from localhost:5000
Upon inspecting, the network tab had 3 or 4 files loaded successfully but some other requests are (pending) forever.
This worked for me perfectly though https://gist.github.com/qhwa/cb9d3851450bff3b705e