Created
September 18, 2013 06:42
-
-
Save oxnz/6605364 to your computer and use it in GitHub Desktop.
get mac addr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <arpa/inet.h> | |
#include <net/if.h> | |
#include <sys/ioctl.h> | |
#include <net/if_dl.h> | |
#include <net/if_types.h> | |
int bsd_get_mac(const char ifname[], uint8_t mac[]) { | |
struct ifreq *ifrp; | |
struct ifconf ifc; | |
char buf[512]; | |
int sockfd, len = 0; | |
ifc.ifc_len = sizeof(buf); | |
ifc.ifc_buf = buf; | |
sockfd = socket(AF_INET, SOCK_DGRAM, 0); | |
if (ioctl(sockfd, SIOCGIFCONF, &ifc) < 0) { | |
perror("ioctl"); | |
return -1; | |
} | |
if (ifc.ifc_len > sizeof(buf)) | |
return 1; | |
ifrp = ifc.ifc_req; | |
do { | |
struct sockaddr *sa = &ifrp->ifr_addr; | |
if (((struct sockaddr_dl *)sa)->sdl_type == IFT_ETHER) { | |
if (strcmp(ifname, ifrp->ifr_name) == 0) { | |
memcpy(mac, LLADDR((struct sockaddr_dl *)&ifrp->ifr_addr), 6); | |
return 0; | |
} | |
} | |
ifrp = (struct ifreq *)(sa->sa_len + (caddr_t)&ifrp->ifr_addr); | |
len += sa->sa_len + sizeof(ifrp->ifr_name); | |
} while (len < ifc.ifc_len); | |
return 0; | |
} | |
int main(void) { | |
uint8_t mac[6]; | |
bsd_get_mac("en0", mac); | |
printf("%02x:%02x:%02x:%02x:%02x:%02x\n", | |
mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment