forked from anacrolix/torrent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ipport.go
71 lines (64 loc) · 1.32 KB
/
ipport.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
package torrent
import (
"net"
"strconv"
)
// Extracts the port as an integer from an address string.
func addrPortOrZero(addr net.Addr) int {
switch raw := addr.(type) {
case *net.UDPAddr:
return raw.Port
case *net.TCPAddr:
return raw.Port
default:
// Consider a unix socket on Windows with a name like "C:notanint".
_, port, err := net.SplitHostPort(addr.String())
if err != nil {
return 0
}
i64, err := strconv.ParseUint(port, 0, 16)
if err != nil {
return 0
}
return int(i64)
}
}
func addrIpOrNil(addr net.Addr) net.IP {
if addr == nil {
return nil
}
switch raw := addr.(type) {
case *net.UDPAddr:
return raw.IP
case *net.TCPAddr:
return raw.IP
default:
host, _, err := net.SplitHostPort(addr.String())
if err != nil {
return nil
}
return net.ParseIP(host)
}
}
type ipPortAddr struct {
IP net.IP
Port int
}
func (ipPortAddr) Network() string {
return ""
}
func (me ipPortAddr) String() string {
return net.JoinHostPort(me.IP.String(), strconv.FormatInt(int64(me.Port), 10))
}
func tryIpPortFromNetAddr(addr PeerRemoteAddr) (ipPortAddr, bool) {
ok := true
host, port, err := net.SplitHostPort(addr.String())
if err != nil {
ok = false
}
portI64, err := strconv.ParseInt(port, 10, 0)
if err != nil {
ok = false
}
return ipPortAddr{net.ParseIP(host), int(portI64)}, ok
}