Home > database >  Linux socket ioctl SIOCGIFNAME No such device error
Linux socket ioctl SIOCGIFNAME No such device error

Time:06-15

I'm trying to get interface name via ioctl:

int sock_fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
struct sockaddr_in addr = { 0 };
struct ifreq if_req = { 0 };

if (sock_fd == -1) {
    perror("socket error");
    return -1;
}

addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("192.168.1.136");

if (bind(sock_fd, (struct sockaddr*) &addr, sizeof(addr)) == -1) {
    perror("bind error");
    return -1;
}

if (ioctl(sock_fd, SIOCGIFNAME, &if_req) == -1) {
    perror("ioctl error");
    return -1;
}

printf("name: %s\nip: %s\n",
                if_req.ifr_ifrn.ifrn_name,
                inet_ntoa(addr.sin_addr)
);

But for some reason ioctl fails with No such device error message. I wonder what is the problem here?

CodePudding user response:

Looking at the documentation, we find the following description for SIOCFIFNAME:

Given the ifr_ifindex, return the name of the interface in ifr_name. This is the only ioctl which returns its result in ifr_name.

In your code, you're initializing ifreq like this:

struct ifreq if_req = { 0 };

So all the values -- including if_req.ifr_ifindex -- are 0. You're asking for the interface name of the device with index 0, but there is no such device. On my system, for example, lo is index 1 and eth0 is index 2:

$ ip -o link
1: lo: ...
2: eth0: ...

That number at the beginning of each line is the interface index.

You may want to take a look at How can I get the interface name/index associated with a TCP socket?, which has some suggestions for mapping a socket to an interface name.

  • Related