endpoint.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "endpoint.h"
  2. #include "sock.h"
  3. TEndpoint::TEndpoint(const TEndpoint::TAddrRef& addr)
  4. : Addr_(addr)
  5. {
  6. const sockaddr* sa = Addr_->Addr();
  7. if (sa->sa_family != AF_INET && sa->sa_family != AF_INET6 && sa->sa_family != AF_UNIX) {
  8. ythrow yexception() << TStringBuf("endpoint can contain only ipv4, ipv6 or unix address");
  9. }
  10. }
  11. TEndpoint::TEndpoint()
  12. : Addr_(new NAddr::TIPv4Addr(TIpAddress(TIpHost(0), TIpPort(0))))
  13. {
  14. }
  15. void TEndpoint::SetPort(ui16 port) {
  16. if (Port() == port || Addr_->Addr()->sa_family == AF_UNIX) {
  17. return;
  18. }
  19. NAddr::TOpaqueAddr* oa = new NAddr::TOpaqueAddr(Addr_.Get());
  20. Addr_.Reset(oa);
  21. sockaddr* sa = oa->MutableAddr();
  22. if (sa->sa_family == AF_INET) {
  23. ((sockaddr_in*)sa)->sin_port = HostToInet(port);
  24. } else {
  25. ((sockaddr_in6*)sa)->sin6_port = HostToInet(port);
  26. }
  27. }
  28. ui16 TEndpoint::Port() const noexcept {
  29. if (Addr_->Addr()->sa_family == AF_UNIX) {
  30. return 0;
  31. }
  32. const sockaddr* sa = Addr_->Addr();
  33. if (sa->sa_family == AF_INET) {
  34. return InetToHost(((const sockaddr_in*)sa)->sin_port);
  35. } else {
  36. return InetToHost(((const sockaddr_in6*)sa)->sin6_port);
  37. }
  38. }
  39. size_t TEndpoint::Hash() const {
  40. const sockaddr* sa = Addr_->Addr();
  41. if (sa->sa_family == AF_INET) {
  42. const sockaddr_in* sa4 = (const sockaddr_in*)sa;
  43. return IntHash((((ui64)sa4->sin_addr.s_addr) << 16) ^ sa4->sin_port);
  44. } else if (sa->sa_family == AF_INET6) {
  45. const sockaddr_in6* sa6 = (const sockaddr_in6*)sa;
  46. const ui64* ptr = (const ui64*)&sa6->sin6_addr;
  47. return IntHash(ptr[0] ^ ptr[1] ^ sa6->sin6_port);
  48. } else {
  49. const sockaddr_un* un = (const sockaddr_un*)sa;
  50. THash<TString> strHash;
  51. return strHash(un->sun_path);
  52. }
  53. }