[libc-commits] [libc] [libc] Implement if_nametoindex and if_indextoname (PR #206082)
Pavel Labath via libc-commits
libc-commits at lists.llvm.org
Tue Jul 7 04:18:09 PDT 2026
================
@@ -0,0 +1,68 @@
+//===----------------------------------------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Linux implementation of if_indextoname.
+///
+//===----------------------------------------------------------------------===//
+
+#include "src/net/if_indextoname.h"
+#include "hdr/errno_macros.h"
+#include "hdr/net_if_macros.h"
+#include "hdr/sys_ioctl_macros.h"
+#include "hdr/sys_socket_macros.h"
+#include "hdr/types/struct_ifreq.h"
+#include "src/__support/CPP/string_view.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/close.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/ioctl.h"
+#include "src/__support/OSUtil/linux/syscall_wrappers/socket.h"
+#include "src/__support/common.h"
+#include "src/__support/libc_errno.h"
+#include "src/__support/macros/null_check.h"
+#include "src/string/memory_utils/inline_memcpy.h"
+#include "src/string/string_utils.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+LLVM_LIBC_FUNCTION(char *, if_indextoname,
+ (unsigned int ifindex, char *ifname)) {
+ LIBC_CRASH_ON_NULLPTR(ifname);
+
+ ErrorOr<int> fd =
+ linux_syscalls::socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0);
+ if (!fd.has_value()) {
+ libc_errno = fd.error();
+ return nullptr;
+ }
+
+ struct ifreq ifr;
+ ifr.ifr_ifindex = static_cast<int>(ifindex);
+
+ ErrorOr<int> ioctl_res = linux_syscalls::ioctl(*fd, SIOCGIFNAME, &ifr);
+
+ linux_syscalls::close(*fd);
----------------
labath wrote:
Done. (I'm assuming you meant to set errno in case of errors, though I can also imagine some sort of an assert as the only way this can fail is if someone closes the FD from underneath us.)
https://github.com/llvm/llvm-project/pull/206082
More information about the libc-commits
mailing list