Initial commit

This commit is contained in:
Torjus Håkestad 2022-02-22 20:22:36 +01:00
commit 8b49d09725
3 changed files with 84 additions and 0 deletions

20
README.md Normal file
View File

@ -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.
```

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module git.t-juice.club/torjus/udprelay
go 1.17

61
main.go Normal file
View File

@ -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())
}
}