vdest.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package core
  2. import (
  3. "net"
  4. "strconv"
  5. )
  6. const (
  7. AddrTypeIP = byte(0x01)
  8. AddrTypeDomain = byte(0x03)
  9. )
  10. type VAddress struct {
  11. Type byte
  12. IP net.IP
  13. Domain string
  14. Port uint16
  15. }
  16. func IPAddress(ip []byte, port uint16) VAddress {
  17. // TODO: check IP length
  18. return VAddress{
  19. AddrTypeIP,
  20. net.IP(ip),
  21. "",
  22. port}
  23. }
  24. func DomainAddress(domain string, port uint16) VAddress {
  25. return VAddress{
  26. AddrTypeDomain,
  27. nil,
  28. domain,
  29. port}
  30. }
  31. func (addr VAddress) IsIPv4() bool {
  32. return addr.Type == AddrTypeIP && len(addr.IP) == net.IPv4len
  33. }
  34. func (addr VAddress) IsIPv6() bool {
  35. return addr.Type == AddrTypeIP && len(addr.IP) == net.IPv6len
  36. }
  37. func (addr VAddress) IsDomain() bool {
  38. return addr.Type == AddrTypeDomain
  39. }
  40. func (addr VAddress) String() string {
  41. var host string
  42. switch addr.Type {
  43. case AddrTypeIP:
  44. host = addr.IP.String()
  45. if len(addr.IP) == net.IPv6len {
  46. host = "[" + host + "]"
  47. }
  48. case AddrTypeDomain:
  49. host = addr.Domain
  50. default:
  51. panic("Unknown Address Type " + strconv.Itoa(int(addr.Type)))
  52. }
  53. return host + ":" + strconv.Itoa(int(addr.Port))
  54. }