destination.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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. case *net.UnixAddr:
  19. // TODO: deal with Unix domain socket
  20. return TCPDestination(LocalHostIP, Port(9))
  21. default:
  22. panic("Net: Unknown address type.")
  23. }
  24. }
  25. // TCPDestination creates a TCP destination with given address
  26. func TCPDestination(address Address, port Port) Destination {
  27. return Destination{
  28. Network: Network_TCP,
  29. Address: address,
  30. Port: port,
  31. }
  32. }
  33. // UDPDestination creates a UDP destination with given address
  34. func UDPDestination(address Address, port Port) Destination {
  35. return Destination{
  36. Network: Network_UDP,
  37. Address: address,
  38. Port: port,
  39. }
  40. }
  41. // NetAddr returns the network address in this Destination in string form.
  42. func (d Destination) NetAddr() string {
  43. return d.Address.String() + ":" + d.Port.String()
  44. }
  45. // String returns the strings form of this Destination.
  46. func (d Destination) String() string {
  47. return d.Network.URLPrefix() + ":" + d.NetAddr()
  48. }
  49. // IsValid returns true if this Destination is valid.
  50. func (d Destination) IsValid() bool {
  51. return d.Network != Network_Unknown
  52. }
  53. // AsDestination converts current Endpoint into Destination.
  54. func (p *Endpoint) AsDestination() Destination {
  55. return Destination{
  56. Network: p.Network,
  57. Address: p.Address.AsAddress(),
  58. Port: Port(p.Port),
  59. }
  60. }