Last active
April 29, 2016 05:52
-
-
Save YutaroHayakawa/61f248191a27eaebbeabfa9cfcb32117 to your computer and use it in GitHub Desktop.
Get ethernet address from interface name in FreeBSD
This file contains hidden or 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 <stdlib.h> | |
#include <string.h> | |
#include <sys/types.h> | |
#include <net/if.h> | |
#include <net/if_dl.h> | |
#include <net/ethernet.h> | |
#include <netinet/in.h> | |
#include <netinet/if_ether.h> | |
#include <ifaddrs.h> | |
#define FORMAT_ETH_ADDR "%02x:%02x:%02x:%02x:%02x:%02x" | |
int get_eth_addr(const char *ifname, struct ether_addr *ethaddr); | |
int main(void) { | |
struct ether_addr ethaddr; | |
if(get_eth_addr("em0", ðaddr) < 0) { | |
fprintf(stderr, "get_eth_addr() failed\n"); | |
exit(EXIT_FAILURE); | |
} | |
printf("MAC Address: " FORMAT_ETH_ADDR "\n", | |
ethaddr.octet[0], ethaddr.octet[1], ethaddr.octet[2], | |
ethaddr.octet[3], ethaddr.octet[4], ethaddr.octet[5]); | |
return 0; | |
} | |
int get_eth_addr(const char *ifname, struct ether_addr *ethaddr) | |
{ | |
struct ifaddrs *ifap; | |
struct ifaddrs *searcher; | |
struct sockaddr_dl *dl_addr; | |
int ret = 0; | |
if((ret = getifaddrs(&ifap)) < 0) { | |
return ret; | |
} | |
searcher = ifap; | |
while(searcher->ifa_next != NULL) { | |
if(strcmp(searcher->ifa_name, ifname) && | |
searcher->ifa_addr->sa_family == AF_LINK) { | |
dl_addr = (struct sockaddr_dl *)searcher->ifa_addr; | |
memcpy(ethaddr->octet, LLADDR(dl_addr), ETHER_ADDR_LEN); | |
ret = 0; | |
break; | |
} | |
searcher = searcher->ifa_next; | |
} | |
if(ret != 0) { | |
ret = -1; | |
} | |
freeifaddrs(ifap); | |
return ret; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment