-
Notifications
You must be signed in to change notification settings - Fork 11
/
main.go
124 lines (100 loc) · 2.37 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package main
import (
"flag"
"fmt"
"log"
"net"
"os"
"strings"
)
const version string = "0.1"
var (
listenAddress = flag.String("listen-address", ":9999", "UDP port to listen for incoming packets")
receiverAddresses = flag.String("receivers", "", "comma seperated list of copy receivers")
bufferSize = flag.Int("buffer-size", 1024, "size of read buffer")
debug = flag.Bool("debug", false, "debug mode")
showVersion = flag.Bool("version", false, "show version info")
)
type receiver struct {
address string
channel chan []byte
}
func init() {
flag.Usage = func() {
fmt.Println("Usage: udp-mirror [ ... ]\n\nParameters:\n")
flag.PrintDefaults()
}
}
func main() {
flag.Parse()
if *showVersion {
printVersion()
os.Exit(0)
}
if len(*receiverAddresses) == 0 {
fmt.Println("No receivers defined!")
os.Exit(1)
}
receivers := getReceivers()
for _, r := range receivers {
go startReceiverWorker(r)
}
startServer(receivers)
}
func printVersion() {
fmt.Println("udp-mirror")
fmt.Printf("Version: %s\n", version)
fmt.Println("Author: Daniel Czerwonk")
fmt.Println("Source code: https://github.com/czerwonk/udp-mirror")
}
func startServer(receivers []*receiver) {
log.Println("Starting listening")
conn, err := net.ListenPacket("udp", *listenAddress)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
log.Printf("Listening on %s. Waiting for packets", *listenAddress)
for {
buf := make([]byte, *bufferSize)
len, _, err := conn.ReadFrom(buf)
if err != nil {
log.Println(err)
}
if *debug {
log.Printf("Received (%d)", len)
}
go func() {
for _, r := range receivers {
r.channel <- buf[:len]
}
}()
}
}
func getReceivers() []*receiver {
receivers := make([]*receiver, 0)
for _, x := range strings.Split(*receiverAddresses, ",") {
r := &receiver{address: strings.TrimSpace(x), channel: make(chan []byte)}
receivers = append(receivers, r)
}
return receivers
}
func startReceiverWorker(r *receiver) {
conn, err := net.Dial("udp", r.address)
if err != nil {
log.Println("Could not connect to receiver %s: %s", r.address, err)
return
}
defer conn.Close()
log.Printf("Adding receiver: %s\n", r.address)
for {
d := <-r.channel
_, err := conn.Write(d)
if err != nil {
log.Printf("%s: %s", r.address, err)
}
if *debug {
log.Printf("Packet sent to %s (%d)", r.address, len(d))
}
}
}