1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 01:57:12 -05:00
v2fly/net/address.go

69 lines
1.2 KiB
Go
Raw Normal View History

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 {
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{
Type: AddrTypeIP,
IP: net.IP(ipCopy),
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{
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))
}