mirror of
https://github.com/RGBCube/serenity
synced 2025-05-14 08:14:58 +00:00
LibC: Implement if_indextoname and if_nametoindex
This commit is contained in:
parent
38dc54317c
commit
1cfc630d13
1 changed files with 38 additions and 4 deletions
|
@ -7,20 +7,54 @@
|
||||||
#include <errno.h>
|
#include <errno.h>
|
||||||
#include <net/if.h>
|
#include <net/if.h>
|
||||||
#include <netinet/in.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_any = IN6ADDR_ANY_INIT;
|
||||||
const in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_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)
|
unsigned int if_nametoindex([[maybe_unused]] char const* ifname)
|
||||||
{
|
{
|
||||||
errno = ENODEV;
|
int dummy_socket = socket(AF_INET, SOCK_DGRAM, 0);
|
||||||
return -1;
|
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)
|
char* if_indextoname([[maybe_unused]] unsigned int ifindex, [[maybe_unused]] char* ifname)
|
||||||
{
|
{
|
||||||
errno = ENXIO;
|
int dummy_socket = socket(AF_INET, SOCK_DGRAM, 0);
|
||||||
return nullptr;
|
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
|
// https://pubs.opengroup.org/onlinepubs/9699919799/functions/if_nameindex.html
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue