From b6aa5bdfab29bf257c1f1ca424c629febd2ca11c Mon Sep 17 00:00:00 2001 From: Bananymous Date: Thu, 7 Aug 2025 02:36:45 +0300 Subject: [PATCH] LibC: Implement if_indextoname and if_nametoindex These are needed for our cmake port --- userspace/libraries/LibC/CMakeLists.txt | 1 + userspace/libraries/LibC/net/if.cpp | 71 +++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 userspace/libraries/LibC/net/if.cpp diff --git a/userspace/libraries/LibC/CMakeLists.txt b/userspace/libraries/LibC/CMakeLists.txt index 532819a7..59ca8610 100644 --- a/userspace/libraries/LibC/CMakeLists.txt +++ b/userspace/libraries/LibC/CMakeLists.txt @@ -20,6 +20,7 @@ set(LIBC_SOURCES locale.cpp malloc.cpp math.cpp + net/if.cpp netdb.cpp netinet/in.cpp poll.cpp diff --git a/userspace/libraries/LibC/net/if.cpp b/userspace/libraries/LibC/net/if.cpp new file mode 100644 index 00000000..03b41294 --- /dev/null +++ b/userspace/libraries/LibC/net/if.cpp @@ -0,0 +1,71 @@ +#include +#include +#include +#include + +static int selector(const dirent* dirent) +{ + if (strcmp(dirent->d_name, "lo") == 0) + return 1; + if (strncmp(dirent->d_name, "eth", 3) == 0) + return 1; + return 0; +} + +static int comparator(const dirent** d1, const dirent** d2) +{ + if (strcmp((*d1)->d_name, "lo")) + return -1; + if (strcmp((*d2)->d_name, "lo")) + return +1; + return alphasort(d1, d2); +} + +char* if_indextoname(unsigned ifindex, char* ifname) +{ + if (ifindex == 0) + return nullptr; + + dirent** namelist; + + const int count = scandir("/dev", &namelist, selector, comparator); + if (count == -1) + return nullptr; + + char* result = nullptr; + if (ifindex - 1 < static_cast(count)) + { + strcpy(ifname, namelist[ifindex - 1]->d_name); + result = ifname; + } + + for (int i = 0; i < count; i++) + free(namelist[i]); + free(namelist); + + return result; +} + +unsigned if_nametoindex(const char* ifname) +{ + dirent** namelist; + + const int count = scandir("/dev", &namelist, selector, comparator); + if (count == -1) + return 0; + + unsigned result = 0; + for (int i = 0; i < count; i++) + { + if (strcmp(ifname, namelist[i]->d_name) != 0) + continue; + result = i + 1; + break; + } + + for (int i = 0; i < count; i++) + free(namelist[i]); + free(namelist); + + return result; +}