-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
nodeaddr.go
75 lines (62 loc) · 1.55 KB
/
nodeaddr.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 krpc
import (
"bytes"
"encoding/binary"
"net"
"net/netip"
"strconv"
"github.com/anacrolix/torrent/bencode"
)
// This will be deprecated in favour of NodeAddrPort.
type NodeAddr struct {
IP net.IP
Port int
}
func (me *NodeAddr) FromAddrPort(f netip.AddrPort) {
me.IP = f.Addr().AsSlice()
me.Port = int(f.Port())
}
func (me NodeAddr) ToNodeAddrPort() NodeAddrPort {
addr, _ := netip.AddrFromSlice(me.IP)
return NodeAddrPort{netip.AddrPortFrom(addr, uint16(me.Port))}
}
// A zero Port is taken to mean no port provided, per BEP 7.
func (me NodeAddr) String() string {
return net.JoinHostPort(me.IP.String(), strconv.FormatInt(int64(me.Port), 10))
}
func (me *NodeAddr) UnmarshalBinary(b []byte) error {
me.IP = make(net.IP, len(b)-2)
copy(me.IP, b[:len(b)-2])
me.Port = int(binary.BigEndian.Uint16(b[len(b)-2:]))
return nil
}
func (me *NodeAddr) UnmarshalBencode(b []byte) (err error) {
var _b []byte
err = bencode.Unmarshal(b, &_b)
if err != nil {
return
}
return me.UnmarshalBinary(_b)
}
func (me NodeAddr) MarshalBinary() ([]byte, error) {
var b bytes.Buffer
b.Write(me.IP)
binary.Write(&b, binary.BigEndian, uint16(me.Port))
return b.Bytes(), nil
}
func (me NodeAddr) MarshalBencode() ([]byte, error) {
return bencodeBytesResult(me.MarshalBinary())
}
func (me NodeAddr) UDP() *net.UDPAddr {
return &net.UDPAddr{
IP: me.IP,
Port: me.Port,
}
}
func (me *NodeAddr) FromUDPAddr(ua *net.UDPAddr) {
me.IP = ua.IP
me.Port = ua.Port
}
func (me NodeAddr) Equal(x NodeAddr) bool {
return me.IP.Equal(x.IP) && me.Port == x.Port
}