1
/* Copyright (C) 2004 MySQL AB
3
This program is free software; you can redistribute it and/or modify
4
it under the terms of the GNU General Public License as published by
5
the Free Software Foundation; version 2 of the License.
7
This program is distributed in the hope that it will be useful,
8
but WITHOUT ANY WARRANTY; without even the implied warranty of
9
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10
GNU General Public License for more details.
12
You should have received a copy of the GNU General Public License
13
along with this program; if not, write to the Free Software
14
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
16
/* get hardware address for an interface */
17
/* if there are many available, any non-zero one can be used */
19
#include "mysys_priv.h"
20
#include <mystrings/m_string.h>
24
#if defined(__FreeBSD__) || defined(__linux__)
25
static bool memcpy_and_test(unsigned char *to, unsigned char *from, uint32_t len)
29
for (i=0; i < len; i++)
34
#endif /* FreeBSD || linux */
38
#include <net/ethernet.h>
39
#include <sys/sysctl.h>
40
#include <net/route.h>
42
#include <net/if_dl.h>
44
bool my_gethwaddr(unsigned char *to)
47
unsigned char *buf, *next, *end, *addr;
48
struct if_msghdr *ifm;
49
struct sockaddr_dl *sdl;
50
int i, res=1, mib[6]={CTL_NET, AF_ROUTE, 0, AF_LINK, NET_RT_IFLIST, 0};
52
if (sysctl(mib, 6, NULL, &len, NULL, 0) == -1)
54
if (!(buf = alloca(len)))
56
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0)
61
for (next = buf ; res && next < end ; next += ifm->ifm_msglen)
63
ifm = (struct if_msghdr *)next;
64
if (ifm->ifm_type == RTM_IFINFO)
66
sdl = (struct sockaddr_dl *)(ifm + 1);
68
res=memcpy_and_test(to, addr, ETHER_ADDR_LEN);
76
#elif defined(__linux__)
79
#include <sys/ioctl.h>
80
#include <net/ethernet.h>
82
bool my_gethwaddr(unsigned char *to)
87
fd = socket(AF_INET, SOCK_DGRAM, 0);
91
memset(&ifr, 0, sizeof(ifr));
92
my_stpncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name) - 1);
95
if (ioctl(fd, SIOCGIFHWADDR, &ifr) >= 0)
96
res=memcpy_and_test(to, (unsigned char *)&ifr.ifr_hwaddr.sa_data, ETHER_ADDR_LEN);
97
} while (res && (errno == 0 || errno == ENODEV) && ifr.ifr_name[3]++ < '6');
104
#else /* FreeBSD elif linux */
106
bool my_gethwaddr(unsigned char *)
113
int main(int argc __attribute__((unused)),char **argv)
115
unsigned char mac[6];
118
if (my_gethwaddr(mac))
120
printf("my_gethwaddr failed with errno %d\n", errno);
123
for (i=0; i < sizeof(mac); i++)
126
printf("%02x", mac[i]);