这个问题和这个问题完全一样:如何使用 C 程序获取机器的 MAC 地址? https://stackoverflow.com/questions/1779715/how-to-get-mac-address-of-your-machine-using-a-c-program
“我正在 Ubuntu 上工作。我如何使用 C 程序获取我的机器的 MAC 地址或接口(如 eth0)。”
现在,我通常不接触 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 地址作为字符串返回的函数,而不是打印 MAC 地址的函数。你知道,像这样:
const char * gettaStringFromNativeCode(void)
{
return "This is a string";
}
这是要与Mozilla 无铬版 https://github.com/mozilla/chromeless,它使用 Firefox 的新 JCTYPES,例如this https://github.com/mozilla/chromeless/tree/master/examples/jsctypes.
基本上,我想做这样的事情(借用 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;
}