glider/proxy/vmess/addr.go

60 lines
1017 B
Go
Raw Normal View History

2018-07-03 00:31:43 +08:00
package vmess
import (
"net"
2022-01-28 23:35:29 +08:00
"net/netip"
2018-07-03 00:31:43 +08:00
"strconv"
)
// Atyp is vmess addr type.
2018-07-07 11:07:38 +08:00
type Atyp byte
2018-07-03 00:31:43 +08:00
// Atyp
const (
2018-07-07 11:07:38 +08:00
AtypErr Atyp = 0
AtypIP4 Atyp = 1
AtypDomain Atyp = 2
AtypIP6 Atyp = 3
2018-07-03 00:31:43 +08:00
)
// Addr is vmess addr.
2018-07-03 00:31:43 +08:00
type Addr []byte
2022-01-28 23:35:29 +08:00
// MaxHostLen is the maximum size of host in bytes.
const MaxHostLen = 255
// Port is vmess addr port.
2018-07-03 00:31:43 +08:00
type Port uint16
// ParseAddr parses the address in string s.
2018-07-07 11:07:38 +08:00
func ParseAddr(s string) (Atyp, Addr, Port, error) {
2018-07-03 00:31:43 +08:00
host, port, err := net.SplitHostPort(s)
if err != nil {
return 0, nil, 0, err
}
2022-01-29 21:10:09 +08:00
var addr Addr
var atyp Atyp = AtypIP4
2022-01-28 23:35:29 +08:00
if ip, err := netip.ParseAddr(host); err == nil {
2022-01-29 21:10:09 +08:00
if ip.Is6() {
2018-07-07 11:07:38 +08:00
atyp = AtypIP6
2018-07-03 00:31:43 +08:00
}
2022-01-28 23:35:29 +08:00
addr = ip.AsSlice()
2018-07-03 00:31:43 +08:00
} else {
2022-01-28 23:35:29 +08:00
if len(host) > MaxHostLen {
2018-07-03 00:31:43 +08:00
return 0, nil, 0, err
}
addr = make([]byte, 1+len(host))
2018-07-07 11:07:38 +08:00
atyp = AtypDomain
2018-07-03 00:31:43 +08:00
addr[0] = byte(len(host))
copy(addr[1:], host)
}
portnum, err := strconv.ParseUint(port, 10, 16)
if err != nil {
return 0, nil, 0, err
}
2018-07-07 11:07:38 +08:00
return atyp, addr, Port(portnum), err
2018-07-03 00:31:43 +08:00
}