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

namespace sibs
{
    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));
    }
    
    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);
    }
}