Date: Mon, 28 Jun 2004 23:45:54 +0800 From: Alecs King <wandys@gawab.com> To: hackers@freebsd.org Subject: Re: Getting MAC address? Message-ID: <20040628154554.GA975@localhost> In-Reply-To: <40DD3EC1.9000106@fer.hr> References: <40DCC57F.5090209@fer.hr> <20040626104947.T93253@woozle.rinet.ru> <40DD3EC1.9000106@fer.hr>
index | next in thread | previous in thread | raw e-mail
On Sat, Jun 26, 2004 at 11:15:45AM +0200, Ivan Voras wrote:
>
> I was looking at it and came across getifaddrs(). This function does not
> depend on a open socket (yes, mine is AF_LINK, sockaddr_dl), and
> apparently returns a list of all interfaces. Is there really no other
> way than to traverse this list?
Back on the days of using FreeBSD 4.6-Release, i once wrote a simple
program to get MAC address of a specified NIC. I tested it on -current
just now. Still works fine. =)
/*
* getmac.c
*
* Simple Demo: Get MAC address of a specified NIC on FreeBSD
*
* To compile: gcc getmac.c -o getmac
*
* Tested on FreeBSD-4.6 RELEASE & FreeBSD-5.2-current
*/
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
int mib[6], len;
char *buf;
unsigned char *ptr;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
if (argc != 2) {
fprintf(stderr, "Usage: getmac <interface>\n");
return 1;
}
mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0;
mib[3] = AF_LINK;
mib[4] = NET_RT_IFLIST;
if ((mib[5] = if_nametoindex(argv[1])) == 0) {
perror("if_nametoindex error");
exit(2);
}
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
perror("sysctl 1 error");
exit(3);
}
if ((buf = malloc(len)) == NULL) {
perror("malloc error");
exit(4);
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
perror("sysctl 2 error");
exit(5);
}
ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned char *)LLADDR(sdl);
printf("%02x:%02x:%02x:%02x:%02x:%02x\n", *ptr, *(ptr+1), *(ptr+2),
*(ptr+3), *(ptr+4), *(ptr+5));
return 0;
}
Reference: UNP v1. Section 17.5
Hope this helps.
--
Alecs King
help
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20040628154554.GA975>
