aboutsummaryrefslogtreecommitdiffstats
path: root/util/network/endpoint.h
blob: 728f5841d5a98f4a851d630fe547579191bd475d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#pragma once

#include "address.h"

#include <util/str_stl.h>

// some equivalent boost::asio::ip::endpoint (easy for using pair ip:port)
class TEndpoint {
public:
    using TAddrRef = NAddr::IRemoteAddrRef;

    TEndpoint(const TAddrRef& addr);
    TEndpoint();

    inline const TAddrRef& Addr() const noexcept {
        return Addr_;
    }
    inline const sockaddr* SockAddr() const {
        return Addr_->Addr();
    }
    inline socklen_t SockAddrLen() const {
        return Addr_->Len();
    }

    inline bool IsIpV4() const {
        return Addr_->Addr()->sa_family == AF_INET;
    }
    inline bool IsIpV6() const {
        return Addr_->Addr()->sa_family == AF_INET6;
    }
    inline bool IsUnix() const {
        return Addr_->Addr()->sa_family == AF_UNIX;
    }

    inline TString IpToString() const {
        return NAddr::PrintHost(*Addr_);
    }

    void SetPort(ui16 port);
    ui16 Port() const noexcept;

    size_t Hash() const;

private:
    TAddrRef Addr_;
};

template <>
struct THash<TEndpoint> {
    inline size_t operator()(const TEndpoint& ep) const {
        return ep.Hash();
    }
};

inline bool operator==(const TEndpoint& l, const TEndpoint& r) {
    try {
        return NAddr::IsSame(*l.Addr(), *r.Addr()) && l.Port() == r.Port();
    } catch (...) {
        return false;
    }
}