1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
| #include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *get_mac_address (char const *iface);
int main (void)
{
char *address = get_mac_address ("eth1");
if (address != NULL)
{
puts (address);
free (address), address = NULL;
}
return EXIT_SUCCESS;
}
char *get_mac_address (char const *iface)
{
char *hwaddr = calloc (18, sizeof *hwaddr);
if (hwaddr != NULL)
{
int fd = socket (AF_INET, SOCK_DGRAM, 0);
if (fd != -1)
{
struct ifreq ifr;
strncpy (ifr.ifr_name, iface, IFNAMSIZ);
if (ioctl (fd, SIOCGIFFLAGS, &ifr) == 0)
{
if (ioctl (fd, SIOCGIFHWADDR, &ifr) == 0)
{
char buf[8];
memcpy (buf, ifr.ifr_hwaddr.sa_data, 8);
snprintf (hwaddr, 18, "%02X:%02X:%02X:%02X:%02X:%02X",
(buf[0] & 0xFF), (buf[1] & 0xFF), (buf[2] & 0xFF),
(buf[3] & 0xFF), (buf[4] & 0xFF), (buf[5] & 0xFF));
}
else
{
perror ("ioctl(SIOCGIFHWADDR)");
}
}
else
{
perror ("ioctl(SIOCGIFFLAGS)");
}
}
else
{
perror ("socket() error");
}
}
return hwaddr;
} |
Partager