destination.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. Port Port
  9. Address Address
  10. }
  11. // DestinationFromAddr generates a Destination from a net address.
  12. func DestinationFromAddr(addr net.Addr) Destination {
  13. switch addr := addr.(type) {
  14. case *net.TCPAddr:
  15. return TCPDestination(IPAddress(addr.IP), Port(addr.Port))
  16. case *net.UDPAddr:
  17. return UDPDestination(IPAddress(addr.IP), Port(addr.Port))
  18. default:
  19. panic("Net: Unknown address type.")
  20. }
  21. }
  22. // TCPDestination creates a TCP destination with given address
  23. func TCPDestination(address Address, port Port) Destination {
  24. return Destination{
  25. Network: Network_TCP,
  26. Address: address,
  27. Port: port,
  28. }
  29. }
  30. // UDPDestination creates a UDP destination with given address
  31. func UDPDestination(address Address, port Port) Destination {
  32. return Destination{
  33. Network: Network_UDP,
  34. Address: address,
  35. Port: port,
  36. }
  37. }
  38. func (v Destination) NetAddr() string {
  39. return v.Address.String() + ":" + v.Port.String()
  40. }
  41. func (v Destination) String() string {
  42. return v.Network.URLPrefix() + ":" + v.NetAddr()
  43. }
  44. func (v Destination) IsValid() bool {
  45. return v.Network != Network_Unknown
  46. }
  47. // AsDestination converts current Enpoint into Destination.
  48. func (v *Endpoint) AsDestination() Destination {
  49. return Destination{
  50. Network: v.Network,
  51. Address: v.Address.AsAddress(),
  52. Port: Port(v.Port),
  53. }
  54. }