destination.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package net
  2. import (
  3. "net"
  4. )
  5. // Destination represents a network destination including address and protocol (tcp / udp).
  6. type Destination struct {
  7. Network Network
  8. Address Address
  9. Port Port
  10. }
  11. func DestinationFromAddr(addr net.Addr) Destination {
  12. switch addr := addr.(type) {
  13. case *net.TCPAddr:
  14. return TCPDestination(IPAddress(addr.IP), Port(addr.Port))
  15. case *net.UDPAddr:
  16. return UDPDestination(IPAddress(addr.IP), Port(addr.Port))
  17. default:
  18. panic("Unknown address type.")
  19. }
  20. }
  21. // TCPDestination creates a TCP destination with given address
  22. func TCPDestination(address Address, port Port) Destination {
  23. return Destination{
  24. Network: Network_TCP,
  25. Address: address,
  26. Port: port,
  27. }
  28. }
  29. // UDPDestination creates a UDP destination with given address
  30. func UDPDestination(address Address, port Port) Destination {
  31. return Destination{
  32. Network: Network_UDP,
  33. Address: address,
  34. Port: port,
  35. }
  36. }
  37. func (v Destination) NetAddr() string {
  38. return v.Address.String() + ":" + v.Port.String()
  39. }
  40. func (v Destination) String() string {
  41. return v.Network.UrlPrefix() + ":" + v.NetAddr()
  42. }
  43. func (v *Endpoint) AsDestination() Destination {
  44. return Destination{
  45. Network: v.Network,
  46. Address: v.Address.AsAddress(),
  47. Port: Port(v.Port),
  48. }
  49. }