aboutsummaryrefslogtreecommitdiff
path: root/src/IpAddress.cpp
blob: 38f758d3d3f0172780997c8acefbfa62c279eed1 (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
#include "../include/sibs/IpAddress.hpp"
#include <cstring>

namespace sibs
{
    Ipv4::Ipv4() : Ipv4(nullptr, 0)
    {
        
    }
    
    Ipv4::Ipv4(const char *ip, unsigned short port)
    {
        address.sin_family = AF_INET;
        address.sin_port = htons(port);
        if(ip)
        {
            if(strlen(ip) > 15)
                throw InvalidAddressException("Ip address is too long");
            
            if(inet_pton(AF_INET, ip, &address.sin_addr.s_addr) != 1)
            {
                std::string errMsg = "Ip ";
                errMsg += ip;
                errMsg += " is not a valid ip";
                throw InvalidAddressException(errMsg);
            }
        }
        else
            address.sin_addr.s_addr = INADDR_ANY;
        memset(address.sin_zero, 0, sizeof(address.sin_zero));
    }
    
    Ipv4::Ipv4(const Ipv4 &other)
    {
        memcpy(&address, &other.address, sizeof(address));
    }
    
    Ipv4& Ipv4::operator = (const Ipv4 &other)
    {
        memcpy(&address, &other.address, sizeof(address));
        return *this;
    }
    
    std::string Ipv4::getAddress() const
    {
        std::string result;
        result.resize(INET_ADDRSTRLEN);
        inet_ntop(AF_INET, &address.sin_addr, &result[0], INET_ADDRSTRLEN);
        return result;
    }
    
    unsigned short Ipv4::getPort() const
    {
        return ntohs(address.sin_port);
    }
}