address.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. ipCopy := make([]byte, len(ip))
  18. copy(ipCopy, ip)
  19. // TODO: check IP length
  20. return Address{
  21. Type: AddrTypeIP,
  22. IP: net.IP(ipCopy),
  23. Domain: "",
  24. Port: port,
  25. }
  26. }
  27. func DomainAddress(domain string, port uint16) Address {
  28. return Address{
  29. Type: AddrTypeDomain,
  30. IP: nil,
  31. Domain: domain,
  32. Port: port,
  33. }
  34. }
  35. func (addr Address) IsIPv4() bool {
  36. return addr.Type == AddrTypeIP && len(addr.IP) == net.IPv4len
  37. }
  38. func (addr Address) IsIPv6() bool {
  39. return addr.Type == AddrTypeIP && len(addr.IP) == net.IPv6len
  40. }
  41. func (addr Address) IsDomain() bool {
  42. return addr.Type == AddrTypeDomain
  43. }
  44. func (addr Address) String() string {
  45. var host string
  46. switch addr.Type {
  47. case AddrTypeIP:
  48. host = addr.IP.String()
  49. if len(addr.IP) == net.IPv6len {
  50. host = "[" + host + "]"
  51. }
  52. case AddrTypeDomain:
  53. host = addr.Domain
  54. default:
  55. panic("Unknown Address Type " + strconv.Itoa(int(addr.Type)))
  56. }
  57. return host + ":" + strconv.Itoa(int(addr.Port))
  58. }