destination.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. Address Address
  8. Port Port
  9. Network Network
  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. // NetAddr returns the network address in this Destination in string form.
  39. func (d Destination) NetAddr() string {
  40. return d.Address.String() + ":" + d.Port.String()
  41. }
  42. // String returns the strings form of this Destination.
  43. func (d Destination) String() string {
  44. return d.Network.URLPrefix() + ":" + d.NetAddr()
  45. }
  46. // IsValid returns true if this Destination is valid.
  47. func (d Destination) IsValid() bool {
  48. return d.Network != Network_Unknown
  49. }
  50. // AsDestination converts current Endpoint into Destination.
  51. func (p *Endpoint) AsDestination() Destination {
  52. return Destination{
  53. Network: p.Network,
  54. Address: p.Address.AsAddress(),
  55. Port: Port(p.Port),
  56. }
  57. }