#include <sys/types.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <net/if.h>
#include <netinet/in.h>
#include <net/if_dl.h>
#include <sys/sysctl.h>
void GetMACAddress(unsigned char *mac)
{
? ??int? ? ? ? ? ? ? ? ?mib[6];
? ? size_t? ? ? ? ? ? ? len;
? ? char? ? ? ? ? ? ? ? *buf;
? ? unsigned char? ? ? ?*ptr;
? ? struct if_msghdr? ? *ifm;
? ? struct sockaddr_dl? *sdl;
?? ?
? ? 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("en0")) == 0) {
? ? ? ? printf("Error: if_nametoindex error/n");
? ? ? ? return ;
? ? }
?? ?
? ? if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
? ? ? ? printf("Error: sysctl, take 1/n");
? ? ? ? return ;
? ? }
?? ?
? ? if ((buf = malloc(len)) == NULL) {
? ? ? ? printf("Could not allocate memory. error!/n");
? ? ? ? return ;
? ? }
?? ?
? ? if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
? ? ? ? printf("Error: sysctl, take 2");
free(buf);
? ? ? ? return ;
? ? }
?? ?
? ? ifm = (struct if_msghdr *)buf;
? ? sdl = (struct sockaddr_dl *)(ifm + 1);
? ? ptr = (unsigned char *)LLADDR(sdl);
? ??memcpy(mac,ptr, 6);
? ? free(buf);
}
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!