Skip to content

Commit 9be1b21

Browse files
committed
Implement if_nametoindex & if_indextoname
1 parent 9336f16 commit 9be1b21

File tree

4 files changed

+64
-0
lines changed

4 files changed

+64
-0
lines changed

include/net/if.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,10 @@ struct sockaddr_hw {
218218
unsigned char shw_addr[8]; /* address */
219219
};
220220

221+
/* Convert an interface name to an index, and vice versa. */
222+
extern unsigned short if_nametoindex (const char *__ifname) __THROW;
223+
extern char *if_indextoname (unsigned short __ifindex, char __ifname[IF_NAMESIZE]) __THROW;
224+
221225
__END_DECLS
222226

223227
#endif /* _NET_IF_H */

socket/SRCFILES

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ SRCFILES = \
3838
hstrerror.c \
3939
hton.c \
4040
ident_sock.c \
41+
if_indextoname.c \
42+
if_nametoindex.c \
4143
inet_addr.c \
4244
inet_lnaof.c \
4345
inet_makeaddr.c \

socket/if_indextoname.c

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#include <net/if.h>
2+
#include <sys/socket.h>
3+
#include <sys/ioctl.h>
4+
#include <string.h>
5+
#include <unistd.h>
6+
#include <errno.h>
7+
8+
__typeof__(if_indextoname) __if_indextoname;
9+
10+
char *
11+
__if_indextoname(unsigned short index, char name[IF_NAMESIZE])
12+
{
13+
struct ifreq ifr;
14+
int fd, r;
15+
16+
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0){
17+
__set_errno (ENXIO);
18+
return NULL;
19+
}
20+
ifr.ifr_ifindex = index;
21+
r = ioctl(fd, SIOCGIFNAME_ETH, &ifr);
22+
close(fd);
23+
if(!r){
24+
return strncpy(name, ifr.ifr_name, IF_NAMESIZE);
25+
}
26+
__set_errno (ENXIO);
27+
return NULL;
28+
}
29+
weak_alias (__if_indextoname, if_indextoname)

socket/if_nametoindex.c

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#include <net/if.h>
2+
#include <sys/socket.h>
3+
#include <sys/ioctl.h>
4+
#include <string.h>
5+
#include <unistd.h>
6+
#include <errno.h>
7+
8+
__typeof__(if_nametoindex) __if_nametoindex;
9+
10+
unsigned short
11+
if_nametoindex(const char *name)
12+
{
13+
struct ifreq ifr;
14+
int fd, r;
15+
16+
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
17+
__set_errno (ENODEV);
18+
return 0;
19+
}
20+
strlcpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
21+
r = ioctl(fd, SIOCGIFINDEX, &ifr);
22+
close(fd);
23+
if(!r){
24+
return ifr.ifr_ifindex;
25+
}
26+
__set_errno (ENODEV);
27+
return 0;
28+
}
29+
weak_alias (__if_nametoindex, if_nametoindex)

0 commit comments

Comments
 (0)