Get list of interfaces using SIOCGIFCONF ioctl
In Category C/C++
The following example shows how the names of all network interfaces can be retrieved using SIOCGIFCONF ioctl. Other ioctls can be used subsequently to retrieve more information like IP address, netmask etc for each interface.
Download: ifacelist.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
int get_iface_list(struct ifconf *ifconf)
{
int sock, rval;
sock = socket(AF_INET,SOCK_STREAM,0);
if(sock < 0)
{
perror("socket");
return (-1);
}
if((rval = ioctl(sock, SIOCGIFCONF , (char*) ifconf )) < 0 )
perror("ioctl(SIOGIFCONF)");
close(sock);
return rval;
}
int main()
{
static struct ifreq ifreqs[20];
struct ifconf ifconf;
int nifaces, i;
memset(&ifconf,0,sizeof(ifconf));
ifconf.ifc_buf = (char*) (ifreqs);
ifconf.ifc_len = sizeof(ifreqs);
if(get_iface_list(&ifconf) < 0) exit(-1);
nifaces = ifconf.ifc_len/sizeof(struct ifreq);
printf("Interfaces (count = %d):\n", nifaces);
for(i = 0; i < nifaces; i++)
{
printf("\t%-10s\n", ifreqs[i].ifr_name);
}
}
Lets us run the above program.
[neo@techpulp ~]$ gcc ifacelist.c -o ifacelist
[neo@techpulp ~]$ ./ifacelist
Interfaces (count = 3):
lo
eth0
eth1
[neo@techpulp ~]$
Hi Neo,
Thanks for this article. It cleared up all my questions on using ioctl function call with SIOCGIFCONF request.
I have made a small modification to your code. It now prints the IP address of all the interfaces configured in the computer.
#include <arpa/inet.h>Code inside main loop:
char ip_addr [ INET_ADDRSTRLEN ] ;struct sockaddr_in *b = (struct sockaddr_in *) &(ifreqs[i].ifr_addr) ;
printf(ā\t%-10s\t%s\nā, ifreqs[i].ifr_name, inet_ntop(AF_INET, & b->sin_addr, ip_addr, sizeof ip_addr));
I am sorry, somehow none of the header file names are visible in the comment that I posted.
Anyway, I only included ‘arpa/inet.h’ header file apart from what was already there in the code.
Warm Regards,
Ganesh
The code within the for loop in ‘main’ function is also missing:
char ip_addr [ INET_ADDRSTRLEN ] ;
struct sockaddr_in *b = (struct sockaddr_in *) &(ifreqs[i].ifr_addr) ;
printf(”\t%-10s\t%s\n”, ifreqs[i].ifr_name, inet_ntop(AF_INET, & b->sin_addr, ip_addr, sizeof ip_addr));
You must use < for < symbol. Similarly > for > symbol. It is HTML way which we can’t be avoid for now.