socket_addr.h 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. #pragma once
  2. #include "hash.h"
  3. #include <util/generic/hash.h>
  4. #include <util/generic/utility.h>
  5. #include <util/network/address.h>
  6. #include <util/network/init.h>
  7. #include <string.h>
  8. namespace NBus {
  9. class TNetAddr;
  10. }
  11. namespace NBus {
  12. namespace NPrivate {
  13. enum EAddrFamily {
  14. ADDR_UNSPEC = AF_UNSPEC,
  15. ADDR_IPV4 = AF_INET,
  16. ADDR_IPV6 = AF_INET6,
  17. };
  18. class TBusIpAddr {
  19. private:
  20. EAddrFamily Af;
  21. union {
  22. in_addr In4;
  23. in6_addr In6;
  24. };
  25. public:
  26. TBusIpAddr() {
  27. Clear();
  28. }
  29. EAddrFamily GetAddrFamily() const {
  30. return Af;
  31. }
  32. void Clear() {
  33. Zero(*this);
  34. }
  35. in_addr GetInAddr() const {
  36. Y_ASSERT(Af == ADDR_IPV4);
  37. return In4;
  38. }
  39. void SetInAddr(const in_addr& in4) {
  40. Clear();
  41. Af = ADDR_IPV4;
  42. In4 = in4;
  43. }
  44. in6_addr GetIn6Addr() const {
  45. Y_ASSERT(Af == ADDR_IPV6);
  46. return In6;
  47. }
  48. void SetIn6Addr(const in6_addr& in6) {
  49. Clear();
  50. Af = ADDR_IPV6;
  51. In6 = in6;
  52. }
  53. bool operator==(const TBusIpAddr& that) const {
  54. return memcmp(this, &that, sizeof(that)) == 0;
  55. }
  56. };
  57. class TBusSocketAddr {
  58. public:
  59. TBusIpAddr IpAddr;
  60. ui16 Port;
  61. //Only makes sense for IPv6 link-local addresses
  62. ui32 IPv6ScopeID;
  63. TBusSocketAddr()
  64. : Port(0)
  65. , IPv6ScopeID(0)
  66. {
  67. }
  68. TBusSocketAddr(const NAddr::IRemoteAddr*);
  69. TBusSocketAddr(const TNetAddr&);
  70. TBusSocketAddr(TStringBuf host, unsigned port);
  71. TNetAddr ToNetAddr() const;
  72. bool operator==(const TBusSocketAddr& that) const {
  73. return IpAddr == that.IpAddr && Port == that.Port;
  74. }
  75. };
  76. }
  77. }
  78. template <>
  79. struct THash<NBus::NPrivate::TBusIpAddr> {
  80. inline size_t operator()(const NBus::NPrivate::TBusIpAddr& a) const {
  81. return ComputeHash(TStringBuf((const char*)&a, sizeof(a)));
  82. }
  83. };
  84. template <>
  85. struct THash<NBus::NPrivate::TBusSocketAddr> {
  86. inline size_t operator()(const NBus::NPrivate::TBusSocketAddr& a) const {
  87. return HashValues(a.IpAddr, a.Port);
  88. }
  89. };