如何使用C程序获取机器的MAC地址?

时间:2011-05-18 23:57:41

标签: c linux chromeless jsctypes

这个问题与此问题完全相同:How to get MAC address of your machine using a C program?

“我正在研究Ubuntu。如何使用C程序获取我的机器或接口的MAC地址。”


现在,我通常不会碰到C ......但在这种情况下,我必须这样做。由于我真的不知道以下代码中发生了什么,这是从上面的答案中得到的,我需要一些帮助。

#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;
}

而不是打印MAC地址的函数我需要一个将其作为字符串返回的函数。你知道,像这样:

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

这将与Mozilla Chromeless一起使用,this使用Firefox的新JCTYPES,如{{3}}。

基本上,我希望做这样的事情(借用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;
}

2 个答案:

答案 0 :(得分:4)

#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);
}

答案 1 :(得分:3)

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;
}