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
|
#include <stdlib.h>
#include <string.h>
#include <malloc.h>
#include <unistd.h>
#include <netinet/in.h>
#include <linux/if_ether.h>
#include <sys/ioctl.h>
#include <net/if.h>
int getDeviceIndex(int sockfd, unsigned char *deviceName) {
struct ifreq ifr;
strncpy(ifr.ifr_name, deviceName, 16);
if (ioctl(sockfd, SIOCGIFINDEX, &ifr) != 0) {
return -1;
}
return ifr.ifr_ifindex;
}
int getDeviceMAC(const int sockfd, const unsigned char *deviceName, unsigned char *mac) {
struct ifreq ifr;
strncpy(ifr.ifr_name, deviceName, 16);
if (ioctl(sockfd, SIOCGIFHWADDR, &ifr) != 0) {
return -1;
}
memcpy(mac, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
return 1;
}
int getDeviceIp(const int sockfd, const unsigned char *deviceName, struct sockaddr_in *ip) {
struct ifconf ifc;
struct ifreq *ifr;
int i,numDevices;
memset(&ifc, 0, sizeof(ifc));
if (ioctl(sockfd, SIOCGIFCONF, &ifc) != 0) {
return -1;
}
if ((ifr = malloc(ifc.ifc_len * 2)) == NULL) {
perror("malloc");
exit(1);
}
ifc.ifc_req = ifr;
if (ioctl(sockfd, SIOCGIFCONF, &ifc) != 0) {
free(ifr);
return -1;
}
numDevices = ifc.ifc_len / sizeof(struct ifreq);
for (i = 0; i < numDevices; ++i) {
if (strcmp(ifr[i].ifr_name, deviceName) == 0) {
memcpy(ip, &(ifr[i].ifr_addr), sizeof(ip));
free(ifr);
return 1;
}
}
free(ifr);
return -1;
}
|