-
Notifications
You must be signed in to change notification settings - Fork 51
/
interfaceListener.go
79 lines (68 loc) · 1.68 KB
/
interfaceListener.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
package GoSNMPServer
import "net"
import "github.com/pkg/errors"
type ISnmpServerListener interface {
SetupLogger(ILogger)
Address() net.Addr
NextSnmp() (snmpbytes []byte, replyer IReplyer, err error)
Shutdown()
}
type IReplyer interface {
ReplyPDU([]byte) error
Shutdown()
}
type UDPListener struct {
conn *net.UDPConn
logger ILogger
}
func NewUDPListener(l3proto, address string) (ISnmpServerListener, error) {
ret := new(UDPListener)
ret.logger = NewDiscardLogger()
udpaddr, err := net.ResolveUDPAddr(l3proto, address)
if err != nil {
return nil, errors.Wrap(err, "ResolveUDPAddr Error")
}
conn, err := net.ListenUDP(l3proto, udpaddr)
if err != nil {
return nil, errors.Wrap(err, "UDP Listen Error")
}
ret.conn = conn
return ret, nil
}
func (udp *UDPListener) SetupLogger(i ILogger) {
udp.logger = i
}
func (udp *UDPListener) Address() net.Addr {
return udp.conn.LocalAddr()
}
func (udp *UDPListener) NextSnmp() ([]byte, IReplyer, error) {
var msg [4096]byte
if udp.conn == nil {
return nil, nil, errors.New("Connection Not Listen")
}
counts, udpAddr, err := udp.conn.ReadFromUDP(msg[:])
if err != nil {
return nil, nil, errors.Wrap(err, "UDP Read Error")
}
udp.logger.Infof("udp request from %v. size=%v", udpAddr, counts)
return msg[:counts], &UDPReplyer{udpAddr, udp.conn}, nil
}
func (udp *UDPListener) Shutdown() {
if udp.conn != nil {
udp.conn.Close()
udp.conn = nil
}
}
type UDPReplyer struct {
target *net.UDPAddr
conn *net.UDPConn
}
func (r *UDPReplyer) ReplyPDU(i []byte) error {
conn := r.conn
_, err := conn.WriteToUDP(i, r.target)
if err != nil {
return errors.Wrap(err, "WriteToUDP")
}
return nil
}
func (r *UDPReplyer) Shutdown() {}