1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-02 20:15:24 +00:00
v2fly/net/address.go

69 lines
1.2 KiB
Go
Raw Normal View History

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