File: get_mac_bsd.c

package info (click to toggle)
libnet-arp-perl 1.0.4-1
  • links: PTS, VCS
  • area: main
  • in suites: squeeze, wheezy
  • size: 180 kB
  • ctags: 181
  • sloc: ansic: 297; perl: 41; makefile: 26
file content (69 lines) | stat: -rwxr-xr-x 1,456 bytes parent folder | download | duplicates (2)
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
59
60
61
62
63
64
65
66
67
68
69
/*
Perl ARP Extension
Get the MAC address of an interface
BSD code

Programmed by Bastian Ballmann
Last update: 09.02.2006

Fixed for FreeBSD by Niels Bakker
Last update: 2007-12-26

This program is free software; you can redistribute 
it and/or modify it under the terms of the 
GNU General Public License version 2 as published 
by the Free Software Foundation.

This program is distributed in the hope that it will 
be useful, but WITHOUT ANY WARRANTY; without even 
the implied warranty of MERCHANTABILITY or FITNESS 
FOR A PARTICULAR PURPOSE. 
See the GNU General Public License for more details. 
*/

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <ifaddrs.h>

#include <net/if_dl.h>
#include <net/if_types.h>
#include <net/ethernet.h>

int get_mac_bsd(u_char *dev, char *mac)
{
  struct ifaddrs *iface, *iffirst;

  if(strlen(mac) > 0)
    strcpy(mac,"unknown");
  else
    return -1;

  if(strlen(dev) == 0)
    return -1;

  strcpy(mac,"unknown");
  if (getifaddrs(&iface))
    return -1;

  iffirst = iface;
  while(iface->ifa_next != NULL)
    {
      if(!strcmp(iface->ifa_name,dev))
	{
	  if (iface->ifa_addr->sa_family == AF_LINK)
	    {
	      struct sockaddr_dl *sdl = (struct sockaddr_dl *) iface->ifa_addr;
	      sprintf(mac, "%s",
		      ether_ntoa((struct ether_addr *)LLADDR(sdl)));
	      break;
	    }
	}

      iface = iface->ifa_next;	
    }

  freeifaddrs(iffirst);
  return 0;
}