Last active
October 11, 2022 10:55
-
-
Save dongnguyenltqb/366497ad130f0afa8b47126c727c1217 to your computer and use it in GitHub Desktop.
tcp port forwarder
This file contains 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" | |
"net" | |
) | |
var port int | |
var remoteAddress string | |
func init() { | |
fmt.Println("Parsing config..") | |
flag.IntVar(&port, "port", 8080, "local port to listen") | |
flag.StringVar(&remoteAddress, "remote", "home.dongnguyen.dev:80", "remote address to forward") | |
flag.Parse() | |
} | |
func main() { | |
fmt.Printf("Start listening on port: %d\nForward to: %s\n", port, remoteAddress) | |
ln, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) | |
if err != nil { | |
panic(err) | |
} | |
for { | |
conn, err := ln.Accept() | |
if err != nil { | |
fmt.Println(err.Error()) | |
} | |
go handleRequest(conn) | |
} | |
} | |
func handleRequest(conn net.Conn) { | |
fmt.Printf("[%s] connecting\n", conn.RemoteAddr().String()) | |
proxy, err := net.Dial("tcp", remoteAddress) | |
if err != nil { | |
fmt.Printf("[%s] error %s\n", conn.RemoteAddr().String(), err.Error()) | |
conn.Close() | |
return | |
} | |
fmt.Printf("[%s] connected\n", conn.RemoteAddr().String()) | |
go copyIO(conn, proxy) | |
go copyIO(proxy, conn) | |
} | |
func copyIO(src, dest net.Conn) { | |
defer src.Close() | |
defer dest.Close() | |
io.Copy(src, dest) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment