-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
66 lines (58 loc) · 1.73 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
package main
import (
"bufio"
"flag"
"net"
"sync"
"github.com/antongulenko/golib"
log "github.com/sirupsen/logrus"
)
func handleTcpConn(_ *sync.WaitGroup, conn *net.TCPConn) {
remote := conn.RemoteAddr()
log.Debugln("Accepted TCP connection from", remote)
b := bufio.NewReader(conn)
for {
line, _, err := b.ReadLine()
if err != nil {
log.Errorf("Error receiving TCP data from %v: %v\n", remote, err)
break
} else {
printData(line, conn.LocalAddr(), remote.String(), "TCP")
}
}
}
func handleUdpPacket(_ *sync.WaitGroup, localAddr net.Addr, remoteAddr *net.UDPAddr, packet []byte) {
printData(packet, localAddr, remoteAddr.String(), "UDP")
}
func printData(data []byte, localAddr net.Addr, remoteAddr string, proto string) {
dataStr := string(data)
if len(dataStr) > 0 && dataStr[len(dataStr)-1] == '\n' {
dataStr = dataStr[:len(dataStr)-1] // Newline will be added by logger
}
log.Printf("[%v] Received on %v from %v (len %v): %v", proto, localAddr, remoteAddr, len(data), dataStr)
}
func main() {
var tcpEndpoints, udpEndpoints golib.StringSlice
flag.Var(&tcpEndpoints, "t", "TCP endpoints to listen on")
flag.Var(&udpEndpoints, "u", "UDP endpoints to listen on")
golib.RegisterFlags(golib.FlagsAll)
flag.Parse()
defer golib.ProfileCpu()()
if len(tcpEndpoints)+len(udpEndpoints) == 0 {
log.Fatalln("Please specify at least one UDP or TCP endpoint to listen on.")
}
var tasks golib.TaskGroup
for _, endpoint := range tcpEndpoints {
tasks.Add(&golib.TCPListenerTask{
ListenEndpoint: endpoint,
Handler: handleTcpConn,
})
}
for _, endpoint := range udpEndpoints {
tasks.Add(&golib.UDPListenerTask{
ListenEndpoint: endpoint,
Handler: handleUdpPacket,
})
}
tasks.PrintWaitAndStop()
}