48b4c725
Peter M. Groen
Setting up Socket-pp
|
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
|
bool inet_address::is_set() const
{
static const auto EMPTY_ADDR = sockaddr_in{};
return std::memcmp(&addr_, &EMPTY_ADDR, SZ) != 0;
}
in_addr_t inet_address::resolve_name(const std::string& saddr)
{
#if !defined(_WIN32)
in_addr ia;
if (::inet_pton(ADDRESS_FAMILY, saddr.c_str(), &ia) == 1)
return ia.s_addr;
#endif
addrinfo *res, hints = addrinfo{};
hints.ai_family = ADDRESS_FAMILY;
hints.ai_socktype = SOCK_STREAM;
int gai_err = ::getaddrinfo(saddr.c_str(), NULL, &hints, &res);
#if !defined(_WIN32)
if (gai_err == EAI_SYSTEM)
throw sys_error();
#endif
if (gai_err != 0)
throw getaddrinfo_error(gai_err, saddr);
auto ipv4 = reinterpret_cast<sockaddr_in*>(res->ai_addr);
auto addr = ipv4->sin_addr.s_addr;
freeaddrinfo(res);
return addr;
}
void inet_address::create(uint32_t addr, in_port_t port)
{
addr_ = sockaddr_in{};
addr_.sin_family = AF_INET;
addr_.sin_addr.s_addr = htonl(addr);
addr_.sin_port = htons(port);
}
void inet_address::create(const std::string& saddr, in_port_t port)
{
addr_ = sockaddr_in{};
addr_.sin_family = AF_INET;
addr_.sin_addr.s_addr = resolve_name(saddr.c_str());
addr_.sin_port = htons(port);
}
string inet_address::to_string() const
{
char buf[INET_ADDRSTRLEN];
auto str = inet_ntop(AF_INET, (void*) &(addr_.sin_addr), buf, INET_ADDRSTRLEN);
return std::string(str ? str : "<unknown>")
+ ":" + std::to_string(unsigned(port()));
}
ostream& operator<<(ostream& os, const inet_address& addr)
{
char buf[INET_ADDRSTRLEN];
auto str = inet_ntop(AF_INET, (void*) &(addr.sockaddr_in_ptr()->sin_addr),
buf, INET_ADDRSTRLEN);
os << (str ? str : "<unknown>") << ":" << unsigned(addr.port());
return os;
}
|