这个问题和这个问题完全一样: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 地址的函数。你知道,像这样:
const char * gettaStringFromNativeCode(void)
{
return "This is a string";
}
这将与使用 Firefox 的新 JCTYPES 的Mozilla Chromeless一起使用。
基本上,我想做这样的事情(借用 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;
}