socket_addr.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "socket_addr.h"
  2. #include "netaddr.h"
  3. #include <util/network/address.h>
  4. #include <util/network/init.h>
  5. #include <util/system/yassert.h>
  6. using namespace NAddr;
  7. using namespace NBus;
  8. using namespace NBus::NPrivate;
  9. static_assert(ADDR_UNSPEC == 0, "expect ADDR_UNSPEC == 0");
  10. NBus::NPrivate::TBusSocketAddr::TBusSocketAddr(const NAddr::IRemoteAddr* addr)
  11. : IPv6ScopeID(0)
  12. {
  13. const sockaddr* sa = addr->Addr();
  14. switch ((EAddrFamily)sa->sa_family) {
  15. case AF_UNSPEC: {
  16. IpAddr.Clear();
  17. Port = 0;
  18. break;
  19. }
  20. case AF_INET: {
  21. IpAddr.SetInAddr(((const sockaddr_in*)sa)->sin_addr);
  22. Port = InetToHost(((const sockaddr_in*)sa)->sin_port);
  23. break;
  24. }
  25. case AF_INET6: {
  26. IpAddr.SetIn6Addr(((const sockaddr_in6*)sa)->sin6_addr);
  27. Port = InetToHost(((const sockaddr_in*)sa)->sin_port);
  28. IPv6ScopeID = InetToHost(((const sockaddr_in6*)sa)->sin6_scope_id);
  29. break;
  30. }
  31. default:
  32. Y_ABORT("unknown address family");
  33. }
  34. }
  35. NBus::NPrivate::TBusSocketAddr::TBusSocketAddr(TStringBuf host, unsigned port) {
  36. *this = TNetAddr(host, port);
  37. }
  38. NBus::NPrivate::TBusSocketAddr::TBusSocketAddr(const TNetAddr& addr) {
  39. *this = TBusSocketAddr(&addr);
  40. }
  41. TNetAddr NBus::NPrivate::TBusSocketAddr::ToNetAddr() const {
  42. sockaddr_storage storage;
  43. Zero(storage);
  44. storage.ss_family = (ui16)IpAddr.GetAddrFamily();
  45. switch (IpAddr.GetAddrFamily()) {
  46. case ADDR_UNSPEC:
  47. return TNetAddr();
  48. case ADDR_IPV4: {
  49. ((sockaddr_in*)&storage)->sin_addr = IpAddr.GetInAddr();
  50. ((sockaddr_in*)&storage)->sin_port = HostToInet(Port);
  51. break;
  52. }
  53. case ADDR_IPV6: {
  54. ((sockaddr_in6*)&storage)->sin6_addr = IpAddr.GetIn6Addr();
  55. ((sockaddr_in6*)&storage)->sin6_port = HostToInet(Port);
  56. ((sockaddr_in6*)&storage)->sin6_scope_id = HostToInet(IPv6ScopeID);
  57. break;
  58. }
  59. }
  60. return TNetAddr(new TOpaqueAddr((sockaddr*)&storage));
  61. }
  62. template <>
  63. void Out<TBusSocketAddr>(IOutputStream& out, const TBusSocketAddr& addr) {
  64. out << addr.ToNetAddr();
  65. }