-
Notifications
You must be signed in to change notification settings - Fork 25
/
data.go
55 lines (46 loc) · 1.14 KB
/
data.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
package udppunch
import (
"encoding/base64"
"fmt"
"net"
)
type Key [32]byte
type Peer [38]byte
var DefaultKey Key
func NewPeerFromAddr(key Key, addr *net.UDPAddr) Peer {
var peer Peer
copy(peer[:], key[:])
copy(peer[32:], addr.IP.To4())
copy(peer[36:], []byte{byte(addr.Port >> 8), byte(addr.Port & 0xff)})
return peer
}
func ParsePeers(buf []byte) []Peer {
peers := make([]Peer, 0, len(buf)/38)
for i := 0; i < len(buf); i += 38 {
var peer Peer
copy(peer[:], buf[i:i+38])
peers = append(peers, peer)
}
return peers
}
func (t Peer) Parse() (key Key, addr string) {
copy(key[:], t[:32])
ip := net.IPv4(t[32], t[33], t[34], t[35]).String()
port := int(t[36])<<8 + int(t[37])
addr = fmt.Sprintf("%s:%d", ip, port)
return
}
func (t Peer) String() string {
key := base64.StdEncoding.EncodeToString(t[:32])
ip := net.IPv4(t[32], t[33], t[34], t[35]).String()
return fmt.Sprintf("%s %s:%d", key, ip, int(t[36])<<8+int(t[37]))
}
func NewKeyFromStr(pubKey string) Key {
b, _ := base64.StdEncoding.DecodeString(pubKey)
var key Key
copy(key[:], b)
return key
}
func (t Key) String() string {
return base64.StdEncoding.EncodeToString(t[:])
}