Hi, All. I want to use a Linux computer for remote data acquisition and decided to use MAC as it's unique ID. I thought, that it would be simple to get it programmatically, but couldn't. Of course, I can run "ifconfig", read it and insert into my program settings, but maybe there is some gcc library function or some generally known trick? I'm really, very inexperienced in Linux. Thanks, Alex.
Programmatical determination of Network card MAC
Jul 24, 2004
5 Replies
You can also do that programmatically, by parsing the output of ifconfig.
The code you need to read it directly is found in the source for ethtool and ifconfig too for that matter. But it's simple enough. Email me and I will give you a sourcecode snippet (I'm not on my Linux box right now).
Poke around in /proc/net if you feel like saving the cost of a popen() or system(). Frankly, though, this routine will probably run so seldom that time spent optimising it is time wasted.
Kelly
I didn't want to suggest /proc because it's possible in an embedded system (in particular) that there may be no /proc filesystem.
Just ripped out the following from an older project...
#ifndef FAKED_IDENTITY // set an default mac... memcpy (my_mac, fake_mac, sizeof (my_mac)); success = 0;
if ((sockfd = socket (AF_INET, SOCK_DGRAM, 0)) >= 0) { strncpy (ifr.ifr_name, "eth0", IFNAMSIZ); memset (&ifr.ifr_hwaddr, 0, sizeof (struct sockaddr)); if (ioctl (sockfd, SIOCGIFHWADDR, &ifr) >= 0) { memcpy (&hwaddr, &ifr.ifr_hwaddr, sizeof (hwaddr)); memcpy (&my_mac, &hwaddr.sa_data, sizeof (my_mac)); success = 1; }
close (sockfd); }
if (success) log (SLOG_BASE+1, "hwaddr(%s): %02x:%02x:%02x:%02x:%02x:%02x", ifr.ifr_name, my_mac[0], my_mac[1], my_mac[2], my_mac[3], my_mac[4], my_mac[5]); else log (SLOG_ERR, "failed to determine hw addr"); #endif
Hope you've got sockets ;-)
HTH. Salut, Jörg
gpg/pgp key # 0xe40a9d7a
fingerprint d4f8 b448 835b 7bcf 4161 ce35 7e8b ab47 e40a 9d7a
to
in
Join the Discussion
Have something to add? Share your thoughts — no account required.
Didn't find your answer?
Ask the community — no account required