-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathNetworkRoster.cpp
90 lines (67 loc) · 1.33 KB
/
NetworkRoster.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
/*
* NetworkInterfaceRoster.cpp
*
* Created on: 12 ott 2015
* Author: Stefano Ceccherini
*/
#include "NetworkRoster.h"
#include "NetworkInterface.h"
#include "Support.h"
#include <errno.h>
#ifndef _BSD_SOURCE
#define _BSD_SOURCE
#endif
#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()
{
_RefreshInterfaces();
}
NetworkRoster::~NetworkRoster()
{
}
int
NetworkRoster::CountInterfaces(int family)
{
_RefreshInterfaces();
return fInterfaces.size();
}
int
NetworkRoster::GetNextInterface(unsigned int* cookie, NetworkInterface& interface)
{
if (cookie == NULL)
return -1;
int index = *cookie;
try {
interface = NetworkInterface(fInterfaces.at(index).c_str());
} catch (...) {
return -1;
}
*cookie = index + 1;
return 0;
}
int
NetworkRoster::_RefreshInterfaces()
{
fInterfaces.clear();
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);
std::set<std::string>::const_iterator i;
for (i = interfaces.begin(); i != interfaces.end(); i++)
fInterfaces.push_back((*i));
return 0;
}