-
-
Notifications
You must be signed in to change notification settings - Fork 628
/
netip-addrport.go
52 lines (45 loc) · 1.15 KB
/
netip-addrport.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
package torrent
import (
"fmt"
"net/netip"
"github.com/anacrolix/dht/v2/krpc"
)
type addrPorter interface {
AddrPort() netip.AddrPort
}
func ipv4AddrPortFromKrpcNodeAddr(na krpc.NodeAddr) (_ netip.AddrPort, err error) {
ip4 := na.IP.To4()
if ip4 == nil {
err = fmt.Errorf("not an ipv4 address: %v", na.IP)
return
}
addr := netip.AddrFrom4(*(*[4]byte)(ip4))
addrPort := netip.AddrPortFrom(addr, uint16(na.Port))
return addrPort, nil
}
func ipv6AddrPortFromKrpcNodeAddr(na krpc.NodeAddr) (_ netip.AddrPort, err error) {
ip6 := na.IP.To16()
if ip6 == nil {
err = fmt.Errorf("not an ipv4 address: %v", na.IP)
return
}
addr := netip.AddrFrom16(*(*[16]byte)(ip6))
addrPort := netip.AddrPortFrom(addr, uint16(na.Port))
return addrPort, nil
}
func addrPortFromPeerRemoteAddr(pra PeerRemoteAddr) (netip.AddrPort, error) {
switch v := pra.(type) {
case addrPorter:
return v.AddrPort(), nil
case netip.AddrPort:
return v, nil
default:
return netip.ParseAddrPort(pra.String())
}
}
func krpcNodeAddrFromAddrPort(addrPort netip.AddrPort) krpc.NodeAddr {
return krpc.NodeAddr{
IP: addrPort.Addr().AsSlice(),
Port: int(addrPort.Port()),
}
}