-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetif_name.c
More file actions
73 lines (56 loc) · 1.94 KB
/
getif_name.c
File metadata and controls
73 lines (56 loc) · 1.94 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
/*
* name: getif_name.c
* this file is part of the "Net-Injector" project. It defines the getif_name_by_ip() function
* Adapted from Salvatore Sanfilippo <antirez@invece.org>
* license: This software is under GPL license
* date: 04 17 2003
* rev: 0.8
*/
#include "neti.h"
int getif_name_by_ip(char *ifname, u_int32_t *inet_ip){
int sock;
struct ifconf ifc;
struct ifreq ibuf[16], ifr, *ifrp, *ifend;
struct sockaddr_in if_sockaddr;
if ( (sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
fprintf(stderr, "Error : (getif_name) socket(AF_INET, SOCK_DGRAM, 0) !\n");
return EXIT_FAILURE;
}
memset(ibuf, 0, sizeof(struct ifreq)*16);
ifc.ifc_len = sizeof ibuf;
ifc.ifc_buf = (caddr_t) ibuf;
/* gets interfaces list */
if ( ioctl(sock, SIOCGIFCONF, (char*)&ifc) == -1 ||
ifc.ifc_len < sizeof(struct ifreq) ) {
fprintf(stderr, "Error : (getif_name) ioctl(SIOCGIFCONF) !\n");
close(sock);
return EXIT_FAILURE;
}
/* ifrp points to buffer and ifend points to buffer's end */
ifrp = ibuf;
ifend = (struct ifreq*) ((char*)ibuf + ifc.ifc_len);
for (; ifrp < ifend; ifrp++) {
strncpy(ifr.ifr_name, ifrp->ifr_name, sizeof(ifr.ifr_name));
if ( ioctl(sock, SIOCGIFFLAGS, (char*)&ifr) == -1) {
fprintf(stderr, "Error : (getif_name) ioctl(SIOCGIFFLAGS) !\n");
continue;
}
/* Check if down */
if ( !(ifr.ifr_flags & IFF_UP) ) continue;
/* Get the interface address */
if (ioctl(sock, SIOCGIFADDR, (char*)&ifr) == -1) {
fprintf(stderr, "Error : (getif_name) ioctl(SIOCGIFADDR) !\n");
continue;
}
/* Copy it */
memcpy(&if_sockaddr, &ifr.ifr_addr, sizeof(struct sockaddr_in));
/* Check if it is what we are locking for */
if (if_sockaddr.sin_addr.s_addr != *inet_ip) continue;
/* interface found, save if name */
strncpy(ifname, ifr.ifr_name, 32);
close(sock);
return EXIT_SUCCESS;
}
close(sock);
return EXIT_FAILURE;
}