Getting MAC address issue Linux(Ubuntu)
I have got MAC address as under.
struct ifreq ifr;
struct ifreq *IFR;
struct ifconf ifc;
char buf[1024];
int s, i;
int ok = 0;
string macAddr = "";
s = socket(AF_INET, SOCK_DGRAM, 0);
if (s==-1) {
return;
}
ifc.ifc_len = sizeof(buf);
ifc.ifc_buf = buf;
ioctl(s, SIOCGIFCONF, &ifc);
IFR = ifc.ifc_req;
for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++) {
strcpy(ifr.ifr_name, IFR->ifr_name);
if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) {
if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) {
ok = 1;
break;
}
}
}
}
close(s);
int p = sizeof(ifr.ifr_hwaddr.sa_data);
cout<<"\n Size:"<<p<<"\n";
fo开发者_StackOverflow社区r(int i = 0; i < p; i++)
macAddr += ifr.ifr_hwaddr.sa_data[i];
cout<<"\n MAC Address:"<<macAddr<<"\n";
I got ifr.ifr_hwaddr.sa_data
data proper, but when I print out I am not getting proper value. What can be the issue for it.
The address in sa_data
isn't in text form, it's the raw binary form, so you need to format it as hex yourself. You also can't use sizeof
to get the size of the address as sa_data
is a generically sized array - you need to look at the sa_len
member to get the length of this address. In C you want something like this:
char *separator = "";
for (int i = 0; i < ifr.ifr_hwaddr.sa_len; i++)
{
printf("%s%02x", separator, ifr.ifr_hwaddr.sa_data[i]);
separator = ":";
}
printf("\n");
精彩评论