/
udp.go
78 lines (72 loc) · 1.57 KB
/
udp.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
package main
import (
"log"
"net"
"os"
"io"
)
const (
BUFFER_LIMIT = 2<<16 -1
)
func HandleUDPConnection(con *net.UDPConn,verbose bool) {
chan_remote := readAndWriteUDP(con, os.Stdout,con, nil,verbose)
ra := con.RemoteAddr()
if ra == nil {
ra = <- chan_remote
}
chan_local := readAndWriteUDP(os.Stdin,con,con,ra,verbose)
select {
case <- chan_local:
if verbose {
log.Println("Connection closed from local process")
}
case <- chan_remote:
if verbose {
log.Println("Connection closed from remote process")
}
}
}
func readAndWriteUDP(r io.Reader, w io.Writer, con *net.UDPConn, ra net.Addr,verbose bool) <-chan net.Addr {
buf := make([]byte, BUFFER_LIMIT)
cAddr := make(chan net.Addr)
go func() {
defer func() {
con.Close()
cAddr <- ra
}()
for {
var bytesread int
var errRead,errWrite error
if con, ok := r.(*net.UDPConn); ok {
var addr net.Addr
bytesread, addr, errRead = con.ReadFrom(buf)
if con.RemoteAddr() == nil && ra == nil {
ra = addr
cAddr <- ra
}
} else {
bytesread, errRead = r.Read(buf)
}
if errRead != nil {
if errRead != io.EOF {
if verbose {
log.Println("READ ERROR: ",errRead)
}
}
break
}
if con, ok := w.(*net.UDPConn); ok && con.RemoteAddr() == nil {
_, errWrite = con.WriteTo(buf[0:bytesread], ra)
} else {
_, errWrite = w.Write(buf[0:bytesread])
}
if errWrite != nil {
if verbose {
log.Println("WRITE ERROR: ",errWrite)
}
return
}
}
}()
return cAddr
}