-
Notifications
You must be signed in to change notification settings - Fork 2
/
net.cpp
90 lines (76 loc) · 2.56 KB
/
net.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
// Copyright (C) 2019 by Yuri Victorovich. All rights reserved.
#include <ifaddrs.h>
#include <netdb.h>
#include <stdio.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include "net.h"
#include "util.h"
#include "err.h"
#include <string>
#include <vector>
namespace Net {
//
// iface
//
std::vector<IpInfo> getIfaceIp4Addresses(const std::string &ifaceName) {
std::vector<IpInfo> addrs;
struct ifaddrs *ifap;
int res;
char host[NI_MAXHOST];
char netmask[NI_MAXHOST];
// helpers
auto countBits = [](auto i) {
unsigned cnt = 0;
for (decltype(i) bit = 1; bit; bit <<= 1)
if (i & bit)
cnt++;
return cnt;
};
auto netFromHostAndNatmaskV4 = [countBits](const std::string &host, const std::string &netmask) {
auto hostVec = Util::splitString(host, ".");
auto netmaskVec = Util::splitString(netmask, ".");
unsigned nbits = 0;
std::ostringstream ss;
for (int i = 0; i < 4; i++) {
if (i > 0)
ss << ".";
uint8_t mask = std::stoul(netmaskVec[i]);
ss << (std::stoul(hostVec[i]) & mask);
nbits += countBits(mask);
}
ss << "/" << nbits;
return ss.str();
};
// get all addresses of all interfaces
if (::getifaddrs(&ifap) == -1)
ERR2("network interface", "getifaddrs() failed: " << strerror(errno))
RunAtEnd destroyAddresses([ifap]() {
::freeifaddrs(ifap);
});
// filter only IPv4 addresses for the requested interface
for (struct ifaddrs *a = ifap; a; a = a->ifa_next)
if (a->ifa_addr->sa_family == AF_INET && ::strcmp(a->ifa_name, ifaceName.c_str()) == 0) { // IPv4 for the requested interface
res = ::getnameinfo(a->ifa_addr,
sizeof(struct sockaddr_in),
host, NI_MAXHOST,
nullptr, 0, NI_NUMERICHOST);
if (res != 0)
ERR2("get network interface address", "getnameinfo() failed: " << ::gai_strerror(res));
res = ::getnameinfo(a->ifa_netmask,
sizeof(struct sockaddr_in),
netmask, NI_MAXHOST,
nullptr, 0, NI_NUMERICHOST);
if (res != 0)
ERR2("get network interface address", "getnameinfo() failed: " << ::gai_strerror(res));
addrs.push_back({host, netmask, netFromHostAndNatmaskV4(host, netmask)});
}
return addrs;
}
std::string getNameserverIp() {
return Util::stripTrailingSpace(Util::runCommandGetOutput("grep -i '^nameserver' /etc/resolv.conf | head -n1 | cut -d ' ' -f2", "find nameserver IP address"));
}
}