]> Sergey Matveev's repositories - btrtrc.git/blob - util/addr.go
Rewrite import paths for migration from Bitbucket
[btrtrc.git] / util / addr.go
1 package util
2
3 import (
4         "net"
5         "strconv"
6 )
7
8 // Extracts the port as an integer from an address string.
9 func AddrPort(addr net.Addr) int {
10         switch raw := addr.(type) {
11         case *net.UDPAddr:
12                 return raw.Port
13         default:
14                 _, port, err := net.SplitHostPort(addr.String())
15                 if err != nil {
16                         panic(err)
17                 }
18                 i64, err := strconv.ParseInt(port, 0, 0)
19                 if err != nil {
20                         panic(err)
21                 }
22                 return int(i64)
23         }
24 }
25
26 func AddrIP(addr net.Addr) net.IP {
27         switch raw := addr.(type) {
28         case *net.UDPAddr:
29                 return raw.IP
30         case *net.TCPAddr:
31                 return raw.IP
32         default:
33                 host, _, err := net.SplitHostPort(addr.String())
34                 if err != nil {
35                         panic(err)
36                 }
37                 return net.ParseIP(host)
38         }
39 }