2015-09-13 14:01:50 -04:00
|
|
|
package net
|
2015-09-10 18:24:18 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"net"
|
|
|
|
"strconv"
|
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
AddrTypeIP = byte(0x01)
|
|
|
|
AddrTypeDomain = byte(0x03)
|
|
|
|
)
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
type Address struct {
|
2015-09-10 18:24:18 -04:00
|
|
|
Type byte
|
|
|
|
IP net.IP
|
|
|
|
Domain string
|
|
|
|
Port uint16
|
|
|
|
}
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
func IPAddress(ip []byte, port uint16) Address {
|
2015-09-17 17:00:17 -04:00
|
|
|
ipCopy := make([]byte, len(ip))
|
|
|
|
copy(ipCopy, ip)
|
2015-09-10 18:24:18 -04:00
|
|
|
// TODO: check IP length
|
2015-09-12 16:11:54 -04:00
|
|
|
return Address{
|
2015-09-16 11:07:05 -04:00
|
|
|
Type: AddrTypeIP,
|
2015-09-17 17:00:17 -04:00
|
|
|
IP: net.IP(ipCopy),
|
2015-09-16 11:07:05 -04:00
|
|
|
Domain: "",
|
|
|
|
Port: port,
|
|
|
|
}
|
2015-09-10 18:24:18 -04:00
|
|
|
}
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
func DomainAddress(domain string, port uint16) Address {
|
|
|
|
return Address{
|
2015-09-16 11:07:05 -04:00
|
|
|
Type: AddrTypeDomain,
|
|
|
|
IP: nil,
|
|
|
|
Domain: domain,
|
|
|
|
Port: port,
|
|
|
|
}
|
2015-09-10 18:24:18 -04:00
|
|
|
}
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
func (addr Address) IsIPv4() bool {
|
2015-09-10 18:24:18 -04:00
|
|
|
return addr.Type == AddrTypeIP && len(addr.IP) == net.IPv4len
|
|
|
|
}
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
func (addr Address) IsIPv6() bool {
|
2015-09-10 18:24:18 -04:00
|
|
|
return addr.Type == AddrTypeIP && len(addr.IP) == net.IPv6len
|
|
|
|
}
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
func (addr Address) IsDomain() bool {
|
2015-09-10 18:24:18 -04:00
|
|
|
return addr.Type == AddrTypeDomain
|
|
|
|
}
|
|
|
|
|
2015-09-12 16:11:54 -04:00
|
|
|
func (addr Address) String() string {
|
2015-09-10 18:24:18 -04:00
|
|
|
var host string
|
|
|
|
switch addr.Type {
|
|
|
|
case AddrTypeIP:
|
2015-09-11 08:12:26 -04:00
|
|
|
host = addr.IP.String()
|
|
|
|
if len(addr.IP) == net.IPv6len {
|
|
|
|
host = "[" + host + "]"
|
|
|
|
}
|
|
|
|
|
2015-09-10 18:24:18 -04:00
|
|
|
case AddrTypeDomain:
|
|
|
|
host = addr.Domain
|
|
|
|
default:
|
|
|
|
panic("Unknown Address Type " + strconv.Itoa(int(addr.Type)))
|
|
|
|
}
|
|
|
|
return host + ":" + strconv.Itoa(int(addr.Port))
|
|
|
|
}
|