开发者

Want to get the list all the available interfaces on the system

I want to get the list all the available interfaces on a particular PC along with their types that is wired or wireless. Cur开发者_StackOverflowrently I am doing the following but no success:-

ioctl(sd, SIOCGIFNAME, &ifr);
strncpy(ifname,ifr.ifr_name,IFNAMSIZ);
printf("Interface name :%s\n",ifname);

It will also be good if only names are available.


If you're on ubuntu, as your tags indicate, you can always read /proc/net/dev which has the information you're looking for in it.


ifconfig -a

for all you can see interfaces avalaible lists you don't need script for C code for this,

İf you wanna more information for your interfaces

lspci

You can find your interfaces type and models


The C interface is called ifaddrs, you may include it with:

#include <sys/types.h>
#include <ifaddrs.h>

The functions you are interested in are getifaddrs and once done with the data, freeifaddrs.

struct ifaddrs {
    struct ifaddrs  *ifa_next;    /* Next item in list */
    char            *ifa_name;    /* Name of interface */
    unsigned int     ifa_flags;   /* Flags from SIOCGIFFLAGS */
    struct sockaddr *ifa_addr;    /* Address of interface */
    struct sockaddr *ifa_netmask; /* Netmask of interface */
    union {
        struct sockaddr *ifu_broadaddr;
                         /* Broadcast address of interface */
        struct sockaddr *ifu_dstaddr;
                         /* Point-to-point destination address */
    } ifa_ifu;
#define              ifa_broadaddr ifa_ifu.ifu_broadaddr
#define              ifa_dstaddr   ifa_ifu.ifu_dstaddr
    void            *ifa_data;    /* Address-specific data */
};

This structure includes all the info as the ifconfig command line tool returns.

For C++ users, I suggest you use a deleter like this:

void ifaddrs_deleter(struct ifaddrs * ia)
{
    freeifaddrs(ia);
}

And attach the result of getifaddrs() to it with:

struct ifaddrs * ifa_start(nullptr);
if(getifaddrs(&ifa_start) != 0)
{
    return;
}
// will automatically delete on exception or any return
std::shared_ptr<struct ifaddrs> auto_free(ifa_start, ifaddrs_deleter);


I just use this command for Ubuntu. I am not sure if this work for other distribution.

ls /sys/class/net
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜