9

I want to get the list all the available interfaces on a particular PC along with their types that is wired or wireless. Currently 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.

  • 1
    Getting the type of interface might be hard, but enumerating the interfaces(and their addresses) is pretty straight foreward see http://stackoverflow.com/questions/2021549/get-ip-address-in-c-language or http://stackoverflow.com/questions/3909656/enumerating-each-ip-assigned-to-network-interfaces/3909936 – nos May 13 '11 at 13:33

4 Answers4

20

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.

Wes Hardaker
  • 21,735
  • 2
  • 38
  • 69
12
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

mlissner
  • 17,359
  • 18
  • 106
  • 169
Onuralp
  • 129
  • 4
4

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);
Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
1

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

ls /sys/class/net
jai3232
  • 383
  • 3
  • 6