Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature Request: Provide if_nametoindex in <net/if.h> #1280

Open
edubart opened this issue Sep 7, 2024 · 2 comments
Open

Feature Request: Provide if_nametoindex in <net/if.h> #1280

edubart opened this issue Sep 7, 2024 · 2 comments

Comments

@edubart
Copy link

edubart commented Sep 7, 2024

Feature Description

Provide if_nametoindex and if_indextoname functions in <net/if.h>, see https://man7.org/linux/man-pages/man3/if_nametoindex.3.html

Motivation

I was trying to compile libslirp but I got the error:

slirp.c: In function 'get_dns_addr_resolv_conf':
slirp.c:455:28: error: implicit declaration of function 'if_nametoindex' [-Wimplicit-function-declaration]
  455 |                 if_index = if_nametoindex(c + 1);

Possible Implementation

If not easy to implement, at worst case it could fail and set an error.

@edubart edubart changed the title Feature Request: Feature Request: Provide if_nametoindex in <net/if.h> Sep 7, 2024
@jart
Copy link
Owner

jart commented Sep 26, 2024

This one is a little tricky, SIOCGIFINDEX is only defined on Linux, FreeBSD, and NetBSD. The indices returned by it are inconsistent from the ordering returned by SIOCGIFCONF. I can't find a definition for these functions in Apple's XNU or Libc codebases. I'm also not entirely sure what this function even does or why it's useful. I would need help understanding it better in order to support it.

@jart
Copy link
Owner

jart commented Sep 26, 2024

Here's a definition from Musl you can use that will work on Linux.

unsigned if_nametoindex(const char *name) {
  int fd, rc;
  struct ifreq ifr;
  if ((fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
    return 0;
  strncpy(ifr.ifr_name, name, sizeof ifr.ifr_name);
  rc = ioctl(fd, SIOCGIFINDEX, &ifr);
  close(fd);
  return rc < 0 ? 0 : ifr.ifr_ifindex;
}

char *if_indextoname(unsigned index, char *name) {
  int fd, rc;
  struct ifreq ifr;
  if ((fd = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0)) < 0)
    return 0;
  ifr.ifr_ifindex = index;
  rc = ioctl(fd, SIOCGIFNAME, &ifr);
  close(fd);
  if (rc < 0) {
    if (errno == ENODEV)
      errno = ENXIO;
    return 0;
  }
  return strncpy(name, ifr.ifr_name, IF_NAMESIZE);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants