linux - How to get MAC address of your machine using a C program? -


i working on ubuntu. how can mac address of machine or interface eth0 using c program.

you need iterate on available interfaces on machine, , use ioctl siocgifhwaddr flag mac address. mac address obtained 6-octet binary array. want skip loopback interface.

#include <sys/ioctl.h> #include <net/if.h>  #include <unistd.h> #include <netinet/in.h> #include <string.h>  int main() {     struct ifreq ifr;     struct ifconf ifc;     char buf[1024];     int success = 0;      int sock = socket(af_inet, sock_dgram, ipproto_ip);     if (sock == -1) { /* handle error*/ };      ifc.ifc_len = sizeof(buf);     ifc.ifc_buf = buf;     if (ioctl(sock, siocgifconf, &ifc) == -1) { /* handle error */ }      struct ifreq* = ifc.ifc_req;     const struct ifreq* const end = + (ifc.ifc_len / sizeof(struct ifreq));      (; != end; ++it) {         strcpy(ifr.ifr_name, it->ifr_name);         if (ioctl(sock, siocgifflags, &ifr) == 0) {             if (! (ifr.ifr_flags & iff_loopback)) { // don't count loopback                 if (ioctl(sock, siocgifhwaddr, &ifr) == 0) {                     success = 1;                     break;                 }             }         }         else { /* handle error */ }     }      unsigned char mac_address[6];      if (success) memcpy(mac_address, ifr.ifr_hwaddr.sa_data, 6); } 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -

How to provide Authorization & Authentication using Asp.net, C#? -