File: get_mac_linux.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 (75 lines) | stat: -rwxr-xr-x 1,639 bytes parent folder | download
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
70
71
72
73
74
75
/*
Perl ARP Extension
Get the MAC address of an interface
Linux code

Programmed by Bastian Ballmann
Last update: 09.02.2006

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 <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <net/ethernet.h>    
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <net/if.h>

int get_mac_linux(u_char *dev, char *mac)
{
  int sock;
  struct ifreq iface;
  struct sockaddr_in *addr;
  struct ether_addr ether;
  
  if(strlen(mac) > 0)
    strcpy(mac,"unknown");
  else
    return -1;

  if(strlen(dev) == 0)
    return -1;
  
  strcpy(iface.ifr_name,dev);
  
  // Open a socket
  if((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
      perror("socket");
      return -1;
    }
  else
    {
      // Get the interface hardware address
      if((ioctl(sock, SIOCGIFHWADDR, &iface)) < 0)
	{
	  perror("ioctl SIOCGIFHWADDR");
	  return -1;
	}
      else
	{
	  sprintf(mac,"%02x:%02x:%02x:%02x:%02x:%02x",
		  iface.ifr_hwaddr.sa_data[0] & 0xff, 
		  iface.ifr_hwaddr.sa_data[1] & 0xff,
		  iface.ifr_hwaddr.sa_data[2] & 0xff, 
		  iface.ifr_hwaddr.sa_data[3] & 0xff,
		  iface.ifr_hwaddr.sa_data[4] & 0xff, 
		  iface.ifr_hwaddr.sa_data[5] & 0xff);	
	}
    }

  return 0;
}