Skip to content

Commit

Permalink
Implement if_nametoindex & if_indextoname
Browse files Browse the repository at this point in the history
  • Loading branch information
MedourMehdi committed Sep 3, 2024
1 parent 9336f16 commit 9be1b21
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 0 deletions.
4 changes: 4 additions & 0 deletions include/net/if.h
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,10 @@ struct sockaddr_hw {
unsigned char shw_addr[8]; /* address */
};

/* Convert an interface name to an index, and vice versa. */
extern unsigned short if_nametoindex (const char *__ifname) __THROW;
extern char *if_indextoname (unsigned short __ifindex, char __ifname[IF_NAMESIZE]) __THROW;

__END_DECLS

#endif /* _NET_IF_H */
2 changes: 2 additions & 0 deletions socket/SRCFILES
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ SRCFILES = \
hstrerror.c \
hton.c \
ident_sock.c \
if_indextoname.c \
if_nametoindex.c \
inet_addr.c \
inet_lnaof.c \
inet_makeaddr.c \
Expand Down
29 changes: 29 additions & 0 deletions socket/if_indextoname.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include <net/if.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

__typeof__(if_indextoname) __if_indextoname;

char *
__if_indextoname(unsigned short index, char name[IF_NAMESIZE])
{
struct ifreq ifr;
int fd, r;

if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0){
__set_errno (ENXIO);
return NULL;
}
ifr.ifr_ifindex = index;
r = ioctl(fd, SIOCGIFNAME_ETH, &ifr);
close(fd);
if(!r){
return strncpy(name, ifr.ifr_name, IF_NAMESIZE);
}
__set_errno (ENXIO);
return NULL;
}
weak_alias (__if_indextoname, if_indextoname)
29 changes: 29 additions & 0 deletions socket/if_nametoindex.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#include <net/if.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>

__typeof__(if_nametoindex) __if_nametoindex;

unsigned short
if_nametoindex(const char *name)
{
struct ifreq ifr;
int fd, r;

if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
__set_errno (ENODEV);
return 0;
}
strlcpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
r = ioctl(fd, SIOCGIFINDEX, &ifr);
close(fd);
if(!r){
return ifr.ifr_ifindex;
}
__set_errno (ENODEV);
return 0;
}
weak_alias (__if_nametoindex, if_nametoindex)

0 comments on commit 9be1b21

Please sign in to comment.