forked from grfz/Socket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Address.cpp
115 lines (98 loc) · 2.65 KB
/
Address.cpp
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
* Address.cpp
* This file is part of VallauriSoft
*
* Copyright (C) 2012 - Comina Francesco
*
* VallauriSoft is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* VallauriSoft is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with VallauriSoft; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
#ifndef _ADDRESS_CPP_
#define _ADDRESS_CPP_
#include "Socket.hpp"
namespace Socket
{
void Address::_address(Ip ip, Port port)
{
this->sin_family = AF_INET;
this->ip(ip);
this->port(port);
}
Address::Address()
{
_address("0.0.0.0", 0);
}
Address::Address(Port port)
{
_address("0.0.0.0", port);
}
Address::Address(Ip ip, Port port)
{
_address(ip, port);
}
Address::Address(struct sockaddr_in address)
{
_address(inet_ntoa(address.sin_addr), address.sin_port);
}
Address::Address(const Address &address)
{
this->sin_family = address.sin_family;
this->sin_addr = address.sin_addr;
this->sin_port = address.sin_port;
}
Ip Address::ip(void)
{
return inet_ntoa(this->sin_addr);
}
Ip Address::ip(Ip ip)
{
#ifdef WINDOWS
unsigned long address = inet_addr(ip.c_str());
if (address == INADDR_NONE)
{
stringstream error;
error << "[ip] with [ip=" << ip << "] Invalid ip address provided";
throw SocketException(error.str());
}
else
{
this->sin_addr.S_un.S_addr = address;
}
#else
if (inet_aton(ip.c_str(), &this->sin_addr) == 0)
{
stringstream error;
error << "[ip] with [ip=" << ip << "] Invalid ip address provided";
throw SocketException(error.str());
}
#endif
return this->ip();
}
Port Address::port(void)
{
return ntohs(this->sin_port);
}
Port Address::port(Port port)
{
this->sin_port = htons(port);
return this->port();
}
ostream& operator<< (ostream &out, Address &address)
{
out << address.ip() << ":" << address.port();
return out;
}
}
#endif