-
Notifications
You must be signed in to change notification settings - Fork 932
/
udp_all.go
100 lines (79 loc) · 1.54 KB
/
udp_all.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
package udp
import (
"encoding/json"
"fmt"
"net"
"strconv"
)
type m map[string]interface{}
type Addr struct {
IP net.IP
Port uint16
}
func NewAddr(ip net.IP, port uint16) *Addr {
addr := Addr{IP: make([]byte, net.IPv6len), Port: port}
copy(addr.IP, ip.To16())
return &addr
}
func NewAddrFromString(s string) *Addr {
ip, port, err := ParseIPAndPort(s)
//TODO: handle err
_ = err
return &Addr{IP: ip.To16(), Port: port}
}
func (ua *Addr) Equals(t *Addr) bool {
if t == nil || ua == nil {
return t == nil && ua == nil
}
return ua.IP.Equal(t.IP) && ua.Port == t.Port
}
func (ua *Addr) String() string {
if ua == nil {
return "<nil>"
}
return net.JoinHostPort(ua.IP.String(), fmt.Sprintf("%v", ua.Port))
}
func (ua *Addr) MarshalJSON() ([]byte, error) {
if ua == nil {
return nil, nil
}
return json.Marshal(m{"ip": ua.IP, "port": ua.Port})
}
func (ua *Addr) Copy() *Addr {
if ua == nil {
return nil
}
nu := Addr{
Port: ua.Port,
IP: make(net.IP, len(ua.IP)),
}
copy(nu.IP, ua.IP)
return &nu
}
type AddrSlice []*Addr
func (a AddrSlice) Equal(b AddrSlice) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if !a[i].Equals(b[i]) {
return false
}
}
return true
}
func ParseIPAndPort(s string) (net.IP, uint16, error) {
rIp, sPort, err := net.SplitHostPort(s)
if err != nil {
return nil, 0, err
}
addr, err := net.ResolveIPAddr("ip", rIp)
if err != nil {
return nil, 0, err
}
iPort, err := strconv.Atoi(sPort)
if err != nil {
return nil, 0, err
}
return addr.IP, uint16(iPort), nil
}