List active network cards in linux with C

3

What I'm missing and I do not really know how to do it is list which network cards are active, get the names (example: eth0, eth1), I have a program that already gets the mac and occupies the validation of the eth0 card , but my question is how to list all the others and know if they are active or not, I put the program that I have made, is formed by:

Lic2.h

#ifndef _LIC2_H_
#define _LIC2_H_

#define LIC_OK                       0
#define LIC_NO_ADAPT_NAME_PROVIDED  -1
#define LIC_INVALID_ADAPTER         -2

#ifdef __cplusplus
extern "C" {
#endif

int licGetMacAddress(char * adapter, unsigned char mAddress[6]);

#ifdef __cplusplus
}
#endif

#endif /* LIC2_H_ */

Lic2.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include "Lic2.h"

int licGetMacAddress(char * adapter, unsigned char mAddress[6]) {
int x, i;
int fd;
struct ifreq ifr;
char direcMac[20];

/* Initialices output variable */
memset(mAddress, 0, 6);

/* Validates adapter name */
if (!adapter)
  return LIC_NO_ADAPT_NAME_PROVIDED;
if (!strlen(adapter))
  return LIC_NO_ADAPT_NAME_PROVIDED;

/* Gets adapter's macaddress */
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name , adapter , IFNAMSIZ-1);
ioctl(fd, SIOCGIFHWADDR, &ifr);
close(fd);
memcpy(mAddress, ifr.ifr_hwaddr.sa_data, 6);

/* Verifies if adapter doesn't exist */
x = 0;
for (i = 0; i < 6; i++)
  if (!mAddress[i]) x++;
if (x == 6)
  return LIC_INVALID_ADAPTER;

return LIC_OK;
}

and the "Main" so call it

example.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Lic2.h"

int main () {
int status, i;
unsigned char mAddress[6];

status=licGetMacAddress("eth0", mAddress);
if (status!=LIC_OK) {
  printf("Error al obtener el Mac Address: %d \n", status);
} else {
  printf("Mac Address: ");
  for (i=0; i<6; i++)
    printf("%02X", mAddress[i]);
  printf("\n");
}
return status;
}
    
asked by Edú Arias 25.11.2016 в 20:02
source

1 answer

2

You can use the list of interfaces obtained via getifaddrs .

The call returns all the interfaces, once for each protocol. That is, if eth0 has ipv4 and ipv6, it will appear twice in the list. If you are not interested in duplicates, it is your task to process it to keep a copy of each one.

The call also returns the inactive interfaces, if you are interested only in the active ones at the moment, keep the ones with the flag IFF_UP

The following code should print all interfaces that have an address assigned:

struct ifaddrs *addrs,*tmp;

getifaddrs(&addrs);
tmp = addrs;

while (tmp)
{
    if (tmp->ifa_addr && tmp->ifa_addr->sa_family == AF_PACKET)
        printf("%s\n", tmp->ifa_name);

    tmp = tmp->ifa_next;
}

freeifaddrs(addrs);
    
answered by 25.11.2016 / 22:00
source