Skip to content

Instantly share code, notes, and snippets.

@rustyeddy
Created October 25, 2022 23:51
Show Gist options
  • Save rustyeddy/ff1706ef61cfeb7dafb1a2fef183ead4 to your computer and use it in GitHub Desktop.
Save rustyeddy/ff1706ef61cfeb7dafb1a2fef183ead4 to your computer and use it in GitHub Desktop.
Get MAC address on Linux
int getMacAddr(std::string ifname, char *macaddr) {
// need to open a socket to read the mac address
int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
if (sock == -1) {
auto err = std::string(strerror(errno));
return Status::UnknownError("failed to open socket" + err);
}
struct ifreq ifr;
strcpy(ifr.ifr_name, ifname.c_str());
int err = ioctl(sock, SIOCGIFHWADDR, &ifr);
if (err != 0) {
return err;
}
sprintf(macaddr, "%02x:%02x:%02x:%02x:%02x:%02x\0",
ifr.ifr_addr.sa_data[0], ifr.ifr_addr.sa_data[1], ifr.ifr_addr.sa_data[2],
ifr.ifr_addr.sa_data[3], ifr.ifr_addr.sa_data[4], ifr.ifr_addr.sa_data[5]);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment