forked from d2g/dhcp4client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
inetsock.go
75 lines (62 loc) · 1.38 KB
/
inetsock.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
package dhcp4client
import (
"net"
"time"
)
type inetSock struct {
*net.UDPConn
laddr net.UDPAddr
raddr net.UDPAddr
}
func NewInetSock(options ...func(*inetSock) error) (*inetSock, error) {
c := &inetSock{
laddr: net.UDPAddr{IP: net.IPv4(0, 0, 0, 0), Port: 68},
raddr: net.UDPAddr{IP: net.IPv4bcast, Port: 67},
}
err := c.setOption(options...)
if err != nil {
return nil, err
}
conn, err := net.ListenUDP("udp4", &c.laddr)
if err != nil {
return nil, err
}
c.UDPConn = conn
return c, err
}
func (c *inetSock) setOption(options ...func(*inetSock) error) error {
for _, opt := range options {
if err := opt(c); err != nil {
return err
}
}
return nil
}
func SetLocalAddr(l net.UDPAddr) func(*inetSock) error {
return func(c *inetSock) error {
c.laddr = l
return nil
}
}
func SetRemoteAddr(r net.UDPAddr) func(*inetSock) error {
return func(c *inetSock) error {
c.raddr = r
return nil
}
}
func (c *inetSock) Write(packet []byte) error {
_, err := c.WriteToUDP(packet, &c.raddr)
return err
}
func (c *inetSock) ReadFrom() ([]byte, net.IP, error) {
readBuffer := make([]byte, MaxDHCPLen)
n, source, err := c.ReadFromUDP(readBuffer)
if source != nil {
return readBuffer[:n], source.IP, err
} else {
return readBuffer[:n], net.IP{}, err
}
}
func (c *inetSock) SetReadTimeout(t time.Duration) error {
return c.SetReadDeadline(time.Now().Add(t))
}