From 8b49d09725d77c886a2f88596040d0c9ea471fd6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Torjus=20H=C3=A5kestad?= Date: Tue, 22 Feb 2022 20:22:36 +0100 Subject: [PATCH] Initial commit --- README.md | 20 ++++++++++++++++++ go.mod | 3 +++ main.go | 61 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+) create mode 100644 README.md create mode 100644 go.mod create mode 100644 main.go diff --git a/README.md b/README.md new file mode 100644 index 0000000..ffe9519 --- /dev/null +++ b/README.md @@ -0,0 +1,20 @@ +# udprelay + +Minimal example to show how to relay UDP packets. + + + +## Build + +```text +go build -o udprelay main.go +``` + + +## Usage +```text +./udprelay -addr "127.0.0.1:9998" -dest "192.168.1.10:9999" +2022/02/21 15:41:50 Listening to 127.0.0.1:9998 - Relaying to 192.168.1.10:9999 +... +2022/02/21 15:42:03 3 bytes relayed from 127.0.0.1:64078 to destination. +``` diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..4fea550 --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module git.t-juice.club/torjus/udprelay + +go 1.17 diff --git a/main.go b/main.go new file mode 100644 index 0000000..51d1430 --- /dev/null +++ b/main.go @@ -0,0 +1,61 @@ +package main + +import ( + "flag" + "fmt" + "log" + "net" +) + +func main() { + var addr, dest string + flag.StringVar(&addr, "addr", ":9999", "listen address") + flag.StringVar(&dest, "dest", "", "destination") + + flag.Parse() + + if dest == "" { + fmt.Println("Error: missing -dest") + fmt.Println("run with -h to see options.") + + return + } + + log.Printf("Listening to %s - Relaying to %s", addr, dest) + raddr, err := net.ResolveUDPAddr("udp", dest) + if err != nil { + panic(err) + } + udpConn, err := net.DialUDP("udp", nil, raddr) + if err != nil { + panic(err) + } + defer udpConn.Close() + + laddr, err := net.ResolveUDPAddr("udp", addr) + if err != nil { + panic(err) + } + + l, err := net.ListenUDP("udp", laddr) + if err != nil { + panic(err) + } + defer l.Close() + + for { + buf := make([]byte, 1024) + n, raddr, err := l.ReadFrom(buf) + log.Printf("received packet %d\n", n) + + if err != nil { + panic(err) + } + + if _, err := udpConn.Write(buf[0:n]); err != nil { + log.Printf("error relaying data: %s\n", err) + } + + log.Printf("%d bytes relayed from %s to destination.\n", n, raddr.String()) + } +}