]> Sergey Matveev's repositories - btrtrc.git/blob - ipport.go
Timeout torrentfs CI after 5 minutes
[btrtrc.git] / ipport.go
1 package torrent
2
3 import (
4         "net"
5         "strconv"
6 )
7
8 // Extracts the port as an integer from an address string.
9 func addrPortOrZero(addr net.Addr) int {
10         switch raw := addr.(type) {
11         case *net.UDPAddr:
12                 return raw.Port
13         case *net.TCPAddr:
14                 return raw.Port
15         default:
16                 _, port, err := net.SplitHostPort(addr.String())
17                 if err != nil {
18                         return 0
19                 }
20                 i64, err := strconv.ParseUint(port, 0, 16)
21                 if err != nil {
22                         panic(err)
23                 }
24                 return int(i64)
25         }
26 }
27
28 func addrIpOrNil(addr net.Addr) net.IP {
29         if addr == nil {
30                 return nil
31         }
32         switch raw := addr.(type) {
33         case *net.UDPAddr:
34                 return raw.IP
35         case *net.TCPAddr:
36                 return raw.IP
37         default:
38                 host, _, err := net.SplitHostPort(addr.String())
39                 if err != nil {
40                         return nil
41                 }
42                 return net.ParseIP(host)
43         }
44 }
45
46 type ipPortAddr struct {
47         IP   net.IP
48         Port int
49 }
50
51 func (ipPortAddr) Network() string {
52         return ""
53 }
54
55 func (me ipPortAddr) String() string {
56         return net.JoinHostPort(me.IP.String(), strconv.FormatInt(int64(me.Port), 10))
57 }
58
59 func tryIpPortFromNetAddr(addr PeerRemoteAddr) (ipPortAddr, bool) {
60         ok := true
61         host, port, err := net.SplitHostPort(addr.String())
62         if err != nil {
63                 ok = false
64         }
65         portI64, err := strconv.ParseInt(port, 10, 0)
66         if err != nil {
67                 ok = false
68         }
69         return ipPortAddr{net.ParseIP(host), int(portI64)}, ok
70 }