forked from larroy/uvpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnet.hpp
59 lines (51 loc) · 1.56 KB
/
net.hpp
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 <memory>
#include <sstream>
//#include "../src/cs/config.hpp"
/// Formatted string, allows to use stream operators and returns a std::string with the resulting format
#define fs(x) \
(static_cast<const std::ostringstream&>(((*std::make_unique<std::ostringstream>().get()) << x)).str ())
namespace uvpp
{
typedef sockaddr_in ip4_addr;
typedef sockaddr_in6 ip6_addr;
inline ip4_addr to_ip4_addr(const std::string& ip, int port)
{
ip4_addr result;
int res = 0;
if ((res = uv_ip4_addr(ip.c_str(), port, &result)) != 0)
throw exception(fs("uv_ip4_addr error: " << error(res).str()));
return result;
}
inline ip6_addr to_ip6_addr(const std::string& ip, int port)
{
ip6_addr result;
int res = 0;
if ((res = uv_ip6_addr(ip.c_str(), port, &result)) != 0)
throw exception(fs("uv_ip6_addr error: " << error(res).str()));
return result;
}
inline bool from_ip4_addr(ip4_addr* src, std::string& ip, int& port)
{
char dest[16];
if(uv_ip4_name(src, dest, 16) == 0)
{
ip = dest;
port = static_cast<int>(ntohs(src->sin_port));
return true;
}
return false;
}
inline bool from_ip6_addr(ip6_addr* src, std::string& ip, int& port)
{
char dest[46];
if(uv_ip6_name(src, dest, 46) == 0)
{
ip = dest;
port = static_cast<int>(ntohs(src->sin6_port));
return true;
}
return false;
}
}
#undef fs