2014-11-17 11:20:49 +08:00
|
|
|
package util
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Extracts the port as an integer from an address string.
|
|
|
|
func AddrPort(addr net.Addr) int {
|
2014-12-26 14:16:20 +08:00
|
|
|
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)
|
2014-11-17 11:20:49 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func AddrIP(addr net.Addr) net.IP {
|
2014-12-26 14:16:20 +08:00
|
|
|
switch raw := addr.(type) {
|
|
|
|
case *net.UDPAddr:
|
|
|
|
return raw.IP
|
|
|
|
default:
|
|
|
|
host, _, err := net.SplitHostPort(addr.String())
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
return net.ParseIP(host)
|
2014-11-17 11:20:49 +08:00
|
|
|
}
|
|
|
|
}
|