forked from jackburton79/inventory-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetworkRoster.cpp
More file actions
123 lines (91 loc) · 2.02 KB
/
NetworkRoster.cpp
File metadata and controls
123 lines (91 loc) · 2.02 KB
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
116
117
118
119
120
121
/*
* NetworkInterfaceRoster.cpp
*
* Created on: 12 ott 2015
* Author: stefano
*/
#include "NetworkRoster.h"
#include "NetworkInterface.h"
#include "Support.h"
#include <errno.h>
#include <ifaddrs.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <cstdlib>
#include <iostream>
#include <set>
NetworkRoster::NetworkRoster()
{
}
NetworkRoster::~NetworkRoster()
{
}
int
NetworkRoster::CountInterfaces(int family)
{
ifaddrs* addrs = NULL;
if (getifaddrs(&addrs) != 0)
return errno;
std::set<std::string> interfaces;
ifaddrs* addr = addrs;
while (addr != NULL) {
interfaces.insert(addr->ifa_name);
addr = addr->ifa_next;
}
freeifaddrs(addrs);
return interfaces.size();
}
int
NetworkRoster::GetNextInterface(unsigned int* cookie, NetworkInterface& interface)
{
if (cookie == NULL)
return -1;
int index = *cookie;
index++;
ifreq ifr;
ifr.ifr_ifindex = index;
int fd = ::socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1)
return errno;
if (::ioctl(fd, SIOCGIFNAME, &ifr) == -1) {
::close(fd);
return errno;
}
::close(fd);
interface = NetworkInterface(ifr.ifr_name);
*cookie = index;
return 0;
}
int
NetworkRoster::GetDefaultGateway(const char* interfaceName,
std::string& defaultGateway)
{
popen_streambuf routeBuf("export LC_ALL=C; route -n", "r");
std::istream stream(&routeBuf);
try {
std::string line;
std::getline(stream, line); // Skip Title
// header
std::getline(stream, line);
size_t gatewayPos = line.find("Gateway");
size_t maskPos = line.find("Genmask");
while (std::getline(stream, line) > 0) {
if (line.find(interfaceName) == std::string::npos)
continue;
std::string destination = line.substr(0, gatewayPos);
trim(destination);
std::string gateway = line.substr(gatewayPos, maskPos - gatewayPos);
trim(gateway);
if (gateway == "0.0.0.0") {
//i->network = destination;
} else if (destination == "0.0.0.0") {
defaultGateway = gateway;
break;
}
}
} catch (...) {
}
return true;
}