[libc-commits] [libc] [libc] Read multiple interfaces per netlink message in if_nameindex (PR #213952)
Pavel Labath via libc-commits
libc-commits at lists.llvm.org
Thu Aug 6 05:03:47 PDT 2026
================
@@ -60,38 +61,19 @@ LIBC_INLINE ErrorOr<ssize_t> send_netlink_dump_request(int sockfd) {
/// A reasonable buffer size for netlink messages (see NLMSG_GOODSIZE in the
/// kernel).
constexpr size_t NLMSG_BUFFER_SIZE = 8192;
-} // namespace detail
-
-template <typename Policy>
-LIBC_INLINE ErrorOr<struct if_nameindex *> if_nameindex() {
- ErrorOr<int> fd_or_err =
- Policy::socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE);
- if (!fd_or_err.has_value())
- return Error(fd_or_err.error());
- int fd = *fd_or_err;
- cpp::scope_exit close_fd([fd]() { Policy::close(fd); });
-
- ErrorOr<ssize_t> send_res = detail::send_netlink_dump_request<Policy>(fd);
- if (!send_res.has_value())
- return Error(send_res.error());
-
- // TODO: Figure out if we need to dynamically allocate a buffer.
- alignas(struct nlmsghdr) uint8_t buf[detail::NLMSG_BUFFER_SIZE];
- ErrorOr<ssize_t> recv_res =
- Policy::recvfrom(fd, buf, sizeof(buf), 0, nullptr, nullptr);
- if (!recv_res.has_value())
- return Error(recv_res.error());
- close_fd.release();
- if (ErrorOr<int> close_res = Policy::close(fd); !close_res.has_value())
- return Error(close_res.error());
-
- // TODO: Read more than one message.
- // TODO: Read more than one interface per message.
- // TODO: Deduplicate interfaces to handle restarts.
- auto len = static_cast<size_t>(*recv_res);
- for (auto *nh = reinterpret_cast<struct nlmsghdr *>(buf); NLMSG_OK(nh, len);
- nh = NLMSG_NEXT(nh, len)) {
+struct InterfaceEntry {
+ unsigned int index;
+ char name[IF_NAMESIZE];
+};
----------------
labath wrote:
Not if it increases the size of the structure, but I think I've managed to create a pretty clean solution that replaces the null terminator byte with a size field (same memory footprint, but two strlen calls less).
https://github.com/llvm/llvm-project/pull/213952
More information about the libc-commits
mailing list