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

让人想犯罪 __ 提交于 2020-01-01 00:45:32

问题


This question is exactly like this question: How to get MAC address of your machine using a C program?

"I am working on Ubuntu. How can I get MAC address of my machine or an interface say eth0 using C program."


Now, I don't usually touch C...but in this case I have to. Since I don't really know what is going on in the following code, which was taken from the answer linked to above, I need some help.

#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <netdb.h>
#include <stdio.h>

int main()
{
  struct ifreq s;
  int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

  strcpy(s.ifr_name, "eth0");
  if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
    int i;
    for (i = 0; i < 6; ++i)
      printf(" %02x", (unsigned char) s.ifr_addr.sa_data[i]);
    puts("\n");
    return 0;
  }
  return 1;
}

Instead of a function that prints the MAC Address I need a function that returns it as a string. You know, like this:

const char * gettaStringFromNativeCode(void) 
{
    return "This is a string";
}

This is to be used with Mozilla Chromeless, which uses Firefox's new JCTYPES like this.

Basically, I'm looking to do something like this (borrowing from C#):

// Using "string" here because its pseudo-code and I don't know what i'm doing. :-)
string getMAC()
{
  struct ifreq s;
  int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

  strcpy(s.ifr_name, "eth0");
  var macAddress = string.Empty; // yah, this is actually C#
  if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
    int i;
    for (i = 0; i < 6; ++i)
       // yah, this is a bit of C# too.
      macAddress += string.Format(" %02x", (unsigned char) s.ifr_addr.sa_data[i]) );
  }
  return macAddress;
}

回答1:


#include <sys/socket.h>
#include <sys/ioctl.h>
#include <linux/if.h>
#include <netdb.h>
#include <stdio.h>

char *getmac(char *iface)
{
#define MAC_STRING_LENGTH 13
  char *ret = malloc(MAC_STRING_LENGTH);
  struct ifreq s;
  int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

  strcpy(s.ifr_name, iface);
  if (fd >= 0 && ret && 0 == ioctl(fd, SIOCGIFHWADDR, &s))
  {
    int i;
    for (i = 0; i < 6; ++i)
      snprintf(ret+i*2,MAC_STRING_LENGTH-i*2,"%02x",(unsigned char) s.ifr_addr.sa_data[i]);
  }
  else
  {
    perror("malloc/socket/ioctl failed");
    exit(1);
  }
  return(ret);
}

int main()
{
  char *mac = getmac("eth0");
  printf("%s\n",mac);
  free(mac);
}



回答2:


int getMac(char mac[6])
{
  struct ifreq s;
  int fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);

  strcpy(s.ifr_name, "eth0");
  if (0 == ioctl(fd, SIOCGIFHWADDR, &s)) {
    int i;
    for (i = 0; i < 6; ++i)
      mac[i] = s.ifr_addr.sa_data[i];
    close(fd);
    return 0;
  }
  close(fd);
  return 1;
}


来源:https://stackoverflow.com/questions/6052377/how-to-get-mac-address-of-your-machine-using-a-c-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!