/
addr.go
72 lines (66 loc) · 1.26 KB
/
addr.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
package missinggo
import (
"net"
"strconv"
"strings"
)
type HostMaybePort struct {
Host string
Port int
NoPort bool
}
func (me HostMaybePort) String() string {
if me.NoPort {
return me.Host
}
return net.JoinHostPort(me.Host, strconv.FormatInt(int64(me.Port), 10))
}
func SplitHostPort(hostport string) (ret HostMaybePort) {
host, port, err := net.SplitHostPort(hostport)
if err != nil {
if strings.Contains(err.Error(), "missing port") {
ret.Host = hostport
ret.NoPort = true
return
}
panic(err)
}
i64, err := strconv.ParseInt(port, 0, 0)
ret.Host = host
ret.Port = int(i64)
if err != nil {
ret.NoPort = true
}
return
}
// Extracts the port as an integer from an address string.
func AddrPort(addr net.Addr) int {
switch raw := addr.(type) {
case *net.UDPAddr:
return raw.Port
default:
_, port, err := net.SplitHostPort(addr.String())
if err != nil {
panic(err)
}
i64, err := strconv.ParseInt(port, 0, 0)
if err != nil {
panic(err)
}
return int(i64)
}
}
func AddrIP(addr net.Addr) net.IP {
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 {
panic(err)
}
return net.ParseIP(host)
}
}