addr.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package yamux
  2. import (
  3. "fmt"
  4. "net"
  5. )
  6. // hasAddr is used to get the address from the underlying connection
  7. type hasAddr interface {
  8. LocalAddr() net.Addr
  9. RemoteAddr() net.Addr
  10. }
  11. // yamuxAddr is used when we cannot get the underlying address
  12. type yamuxAddr struct {
  13. Addr string
  14. }
  15. func (*yamuxAddr) Network() string {
  16. return "yamux"
  17. }
  18. func (y *yamuxAddr) String() string {
  19. return fmt.Sprintf("yamux:%s", y.Addr)
  20. }
  21. // Addr is used to get the address of the listener.
  22. func (s *Session) Addr() net.Addr {
  23. return s.LocalAddr()
  24. }
  25. // LocalAddr is used to get the local address of the
  26. // underlying connection.
  27. func (s *Session) LocalAddr() net.Addr {
  28. addr, ok := s.conn.(hasAddr)
  29. if !ok {
  30. return &yamuxAddr{"local"}
  31. }
  32. return addr.LocalAddr()
  33. }
  34. // RemoteAddr is used to get the address of remote end
  35. // of the underlying connection
  36. func (s *Session) RemoteAddr() net.Addr {
  37. addr, ok := s.conn.(hasAddr)
  38. if !ok {
  39. return &yamuxAddr{"remote"}
  40. }
  41. return addr.RemoteAddr()
  42. }
  43. // LocalAddr returns the local address
  44. func (s *Stream) LocalAddr() net.Addr {
  45. return s.session.LocalAddr()
  46. }
  47. // RemoteAddr returns the remote address
  48. func (s *Stream) RemoteAddr() net.Addr {
  49. return s.session.RemoteAddr()
  50. }