forked from jackburton79/ocs-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNetworkInterface.cpp
144 lines (109 loc) · 2.38 KB
/
NetworkInterface.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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
/*
* Network.cpp
*
* Created on: 12 ott 2015
* Author: stefano
*/
#include "NetworkInterface.h"
#include <errno.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <net/ethernet.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <iomanip>
#include <iostream>
#include <sstream>
NetworkInterface::NetworkInterface()
{
}
NetworkInterface::NetworkInterface(const char* name)
:
fName(name)
{
if (fName.size() > IFNAMSIZ)
throw "NetworkInterface::NetworkInterface(): Name too long";
}
NetworkInterface::~NetworkInterface()
{
}
std::string
NetworkInterface::Name() const
{
return fName;
}
std::string
NetworkInterface::HardwareAddress() const
{
struct ifreq ifr;
if (_DoRequest(SIOCGIFHWADDR, ifr) != 0)
return "";
struct sockaddr* addr = (struct sockaddr*)&ifr.ifr_hwaddr;
std::ostringstream stream;
for (size_t i = 0; i < ETHER_ADDR_LEN; i++) {
int byte = addr->sa_data[i] & 0xFF;
if (i != 0)
stream << ":";
stream << std::hex << std::setw(2) << std::setfill('0') << byte;
}
return stream.str();
}
std::string
NetworkInterface::IPAddress() const
{
struct ifreq ifr;
if (_DoRequest(SIOCGIFADDR, ifr) != 0)
return "";
struct sockaddr_in* ipaddr = (struct sockaddr_in*)&ifr.ifr_addr;
return inet_ntoa(ipaddr->sin_addr);
}
std::string
NetworkInterface::NetMask() const
{
struct ifreq ifr;
if (_DoRequest(SIOCGIFNETMASK, ifr) != 0)
return "";
struct sockaddr_in* ipaddr = (struct sockaddr_in*)&ifr.ifr_netmask;
return inet_ntoa(ipaddr->sin_addr);
}
std::string
NetworkInterface::BroadcastAddress() const
{
struct ifreq ifr;
if (_DoRequest(SIOCGIFBRDADDR, ifr) != 0)
return "";
struct sockaddr_in* ipaddr = (struct sockaddr_in*)&ifr.ifr_broadaddr;
return inet_ntoa(ipaddr->sin_addr);
}
std::string
NetworkInterface::Type() const
{
// TODO:
return "";
}
std::string
NetworkInterface::Status() const
{
struct ifreq ifr;
if (_DoRequest(SIOCGIFFLAGS, ifr) != 0)
return "";
return ifr.ifr_flags & IFF_UP ? "Up" : "Down";
}
int
NetworkInterface::_DoRequest(int request, struct ifreq& ifr) const
{
size_t ifNameLen = fName.size();
::memcpy(ifr.ifr_name, fName.c_str(), ifNameLen);
ifr.ifr_name[ifNameLen] = 0;
int fd = ::socket(AF_INET, SOCK_DGRAM, 0);
if (fd == -1)
return errno;
int status = 0;
if (ioctl(fd, request, &ifr) == -1)
status = errno;
::close(fd);
return status;
}