LibC: Implement if_indextoname and if_nametoindex

This commit is contained in:
Arda Cinar 2023-01-14 00:16:42 +03:00 committed by Sam Atkins
parent 38dc54317c
commit 1cfc630d13
Notes: sideshowbarker 2024-07-16 21:39:23 +09:00

View File

@ -7,20 +7,54 @@
#include <errno.h>
#include <net/if.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
const in6_addr in6addr_any = IN6ADDR_ANY_INIT;
const in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT;
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/if_nametoindex.html
unsigned int if_nametoindex([[maybe_unused]] char const* ifname)
{
errno = ENODEV;
return -1;
int dummy_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (dummy_socket < 0) {
errno = -dummy_socket;
return 0;
}
struct ifreq ifr;
memcpy(ifr.ifr_name, ifname, IF_NAMESIZE);
int rc = ioctl(dummy_socket, SIOCGIFINDEX, &ifr);
if (rc) {
errno = -rc;
return 0;
}
return ifr.ifr_index;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/if_indextoname.html#tag_16_236
char* if_indextoname([[maybe_unused]] unsigned int ifindex, [[maybe_unused]] char* ifname)
{
errno = ENXIO;
return nullptr;
int dummy_socket = socket(AF_INET, SOCK_DGRAM, 0);
if (dummy_socket < 0) {
errno = -dummy_socket;
return 0;
}
struct ifreq ifr;
ifr.ifr_index = ifindex;
int rc = ioctl(dummy_socket, SIOCGIFNAME, &ifr);
if (rc) {
errno = -rc;
return nullptr;
}
memcpy(ifname, ifr.ifr_name, IF_NAMESIZE);
return ifname;
}
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/if_nameindex.html