ioctl, analog of DeviceIOControl

By | December 4, 2021

Win32 API DeviceIOControl function allows Windows application program to send a control code directly to a specified device driver, requesting the corresponding device to perform the appropriate operation. The application program must be started with administrator privileges. I used DeviceIOcontrol function in many project some of them as xedit and socketspy are mentioned in this blog.
ioctl is similar function for Unix OS platforms. The both functions are using device handle as the first parameter (it could be file descriptor, socket or similar), second parameter is control code of requested operation.
The ioctl example presented below returns ipv4 network interfaces with proper IP address, similar as ifconfig command does:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <<ys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <netinet/in.h>
int main(int n, char ** s)
{
        struct ifconf ifc;
        struct ifreq *ifr;
        char buffer[4096];
        char addrbuf[1024];
        printf("Get list of network interfaces\n");
        int sckt = socket(AF_INET, SOCK_DGRAM, 0);
        if(sckt < 0) {
                perror("socket");
                exit(EXIT_FAILURE);
        }
        ifc.ifc_len = sizeof(buffer);
        ifc.ifc_buf = buffer;
        if (ioctl(sckt, SIOCGIFCONF, &ifc) != 0) {
                 perror("ioctl");
                 exit(EXIT_FAILURE);
        }
        int num = 0;
        const char * ipaddr;
        ifr = (struct ifreq*)buffer;
        while ((char*)ifr < buffer + ifc.ifc_len) {
                ++num;
                ipaddr = inet_ntop(ifr->ifr_addr.sa_family,
                           &((struct sockaddr_in*)&ifr->ifr_addr)->sin_addr,
                           addrbuf, sizeof(addrbuf));
                printf("%d. %s : %s\n", num, ifr->ifr_name, ipaddr);
                ifr = (struct ifreq*)((char*)ifr + sizeof(*ifr));
        }
        close(sckt);
}

Results:


#./ioctltest
Get list of network interfaces
1. lo : 127.0.0.1
2. en0 : 10.24.44.40
3. virbr0 : 192.168.2.122

Leave a Reply

Your email address will not be published. Required fields are marked *