ioctl获取接口名称、IP地址、MAC地址、广播地址等

http://blog.markloiseau.com/2012/02/get-network-interfaces-in-c/
http://www.doctort.org/adam/nerd-notes/enumerating-network-interfaces-on-linux.html
http://www.geekpage.jp/en/programming/linux-network/get-ipaddr.php

 
 
 
#include <sys/ioctl.h>
#include <net/if.h>
#include <netinet/in.h>
#include <stdio.h>
#include <arpa/inet.h>

/* 自定义一个结构体存放需要的接口信息。*/
struct ifi_info {
	char *ifi_name;
//	char ifi_name[IFNAMSIZ];		/* interface name, null-terminated */
	struct sockaddr ifi_addr;		/* primary address */
	u_char ifi_haddr[8];			/* hardware address*/
	short ifi_index;				/* interface index */
};

int main(void)
{
    char          buf[1024];
    struct ifconf ifc;
    struct ifreq *ifr;
    int           sck;
    int           nInterfaces;
    int           i;

    struct ifi_info myifi_info[10];

    /* Get a socket handle. */
    sck = socket(AF_INET, SOCK_DGRAM, 0);
    if(sck < 0)
    {
        perror("socket");
        return 1;
    }

    /* Query available interfaces. */
    ifc.ifc_len = sizeof(buf);
    ifc.ifc_buf = buf;
    if(ioctl(sck, SIOCGIFCONF, &ifc) < 0)
    {
        perror("ioctl(SIOCGIFCONF)");
        return 1;
    }

    /* Iterate through the list of interfaces. */
    ifr         = ifc.ifc_req;
    nInterfaces = ifc.ifc_len / sizeof(struct ifreq);
    for(i = 0; i < nInterfaces; i++)
    {
        struct ifreq *item = &ifr[i];
        myifi_info[i].ifi_name = item->ifr_name;
        myifi_info[i].ifi_addr = item->ifr_addr;

        /* Show the device name and IP address */
        printf("%s: IP %s",
        		myifi_info[i].ifi_name,
               inet_ntoa(((struct sockaddr_in *)&(myifi_info[i].ifi_addr))->sin_addr));

        /* Get the MAC address */
        if(ioctl(sck, SIOCGIFHWADDR, item) < 0)
        {
            perror("ioctl(SIOCGIFHWADDR)");
            return 1;
        }

//      myifi_info.ifi_haddr = &(item->ifr_hwaddr).sa_data;

        /* Get the broadcast address (added by Eric)*/
        if(ioctl(sck, SIOCGIFBRDADDR, item) >= 0)
            printf(", BROADCAST %s", inet_ntoa(((struct sockaddr_in *)&item->ifr_broadaddr)->sin_addr));
        printf("\n");

    }//end for

        return 0;
}
原文地址:https://www.cnblogs.com/helloweworld/p/2779671.html