address.go 1.1 KB

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