aboutsummaryrefslogtreecommitdiff
path: root/include/sibs/IpAddress.hpp
blob: ea2a7bdba3dde46e8e4a0e80a98671eee6b244e5 (plain)
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
#pragma once

#include <stdexcept>
#include <string>
#include <unordered_map>
#include "../env.hpp"
#include "../types.hpp"
#if OS_FAMILY != OS_FAMILY_WINDOWS
    #include <arpa/inet.h>
    #include <netdb.h>
#else
    #include <winsock2.h>
    #include <ws2tcpip.h>
    int inet_pton(int af, const char *src, void *dst);
    int inet_pton4(const char *src, void *dst);
    int inet_pton6(const char *src, void *dst);
    typedef u_short sa_family_t;
    typedef uint32_t in_addr_t;
#endif

namespace sibs
{
    class InvalidAddressException : public std::runtime_error
    {
    public:
        InvalidAddressException(const std::string &errMsg) : std::runtime_error(errMsg) {}
    };
    
    class Ipv4
    {
    public:
        Ipv4();
        // If @ip is nullptr, then bind to all available sockets (typical for servers)
        // Throws InvalidAddressException on error.
        Ipv4(const char *ip, unsigned short port);
        Ipv4(u16 family, u32 address, u16 port);
        Ipv4(const Ipv4 &other);
        Ipv4& operator = (const Ipv4 &other);
        
        std::string getAddress() const;
        unsigned short getPort() const;

        bool operator == (const Ipv4 &other) const;
        bool operator != (const Ipv4 &other) const;
        
        struct sockaddr_in address;
    };

    struct Ipv4Hasher
    {
        size_t operator()(const Ipv4 &address) const
        {
            return address.address.sin_addr.s_addr ^ address.address.sin_port;
        }
    };
    
    template <typename ValueType>
    using Ipv4Map = std::unordered_map<Ipv4, ValueType, Ipv4Hasher>;
}