Created
August 29, 2019 07:09
-
-
Save doracl/e2227f3420e0c3e3c7115bca475d102b to your computer and use it in GitHub Desktop.
golang tcp forward proxy
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 ( | |
| "io" | |
| "log" | |
| "net" | |
| ) | |
| var localServerHost = "localhost:8880" | |
| var remoteServerHost = "www.facebook.com:80" | |
| func main() { | |
| ln, err := net.Listen("tcp", localServerHost) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| log.Println("Port forwarding server up and listening on ", localServerHost) | |
| for { | |
| conn, err := ln.Accept() | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| go handleConnection(conn) | |
| } | |
| } | |
| func forward(src, dest net.Conn) { | |
| defer src.Close() | |
| defer dest.Close() | |
| io.Copy(src, dest) | |
| } | |
| func handleConnection(c net.Conn) { | |
| log.Println("Connection from : ", c.RemoteAddr()) | |
| remote, err := net.Dial("tcp", remoteServerHost) | |
| if err != nil { | |
| log.Fatal(err) | |
| } | |
| log.Println("Connected to ", remoteServerHost) | |
| // go routines to initiate bi-directional communication for local server with a | |
| // remote server | |
| go forward(c, remote) | |
| go forward(remote, c) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment