Skip to content

Instantly share code, notes, and snippets.

@matheusfillipe
Last active May 3, 2022 05:31
Show Gist options
  • Save matheusfillipe/a72e9e5fa8b9d8436ffd23dd098263d9 to your computer and use it in GitHub Desktop.
Save matheusfillipe/a72e9e5fa8b9d8436ffd23dd098263d9 to your computer and use it in GitHub Desktop.
Go port fowarding
package main
import (
"os"
"bufio"
"fmt"
"log"
"net"
)
const DEBUG = false
const BIND_PORT = "6666"
const BIND_HOST = "0.0.0.0"
const FORWARD_PORT = "6667"
const FORWARD_HOST = "irc.dot.org.es"
// Server ...
type Server struct {
host string
port string
}
// Client ...
type Client struct {
conn net.Conn
}
// Config ...
type Config struct {
Host string
Port string
}
// New ...
func New(config *Config) *Server {
return &Server{
host: config.Host,
port: config.Port,
}
}
// Run ...
func (server *Server) Run() {
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%s", server.host, server.port))
if err != nil {
log.Fatal(err)
}
defer listener.Close()
for {
conn, err := listener.Accept()
if err != nil {
log.Fatal(err)
}
client := &Client{
conn: conn,
}
go client.handleRequest()
}
}
func foward_client(bind_conn net.Conn) net.Conn {
tcpAddr, err := net.ResolveTCPAddr("tcp", FORWARD_HOST + ":" + FORWARD_PORT)
if err != nil {
println("ResolveTCPAddr failed:", err.Error())
os.Exit(1)
}
conn, err := net.DialTCP("tcp", nil, tcpAddr)
if err != nil {
println("Dial failed:", err.Error())
os.Exit(1)
}
go func(){
for {
reader := bufio.NewReader(conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
println("Write to server failed:", err.Error())
bind_conn.Close()
return
}
if (DEBUG) {
fmt.Printf("Server message: %s", string(message))
}
bind_conn.Write([]byte(message + "\n"))
}
}
}()
return conn
}
func (client *Client) handleRequest() {
server_conn := foward_client(client.conn)
defer server_conn.Close()
reader := bufio.NewReader(client.conn)
for {
message, err := reader.ReadString('\n')
if err != nil {
client.conn.Close()
return
}
if (DEBUG) {
fmt.Printf("Message incoming: %s", string(message))
}
server_conn.Write([]byte(message + "\n"))
}
}
func main() {
server := New(&Config{
Host: BIND_HOST,
Port: BIND_PORT,
})
server.Run()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment