此问题与此问题完全相同:How to get MAC address of your machine using a C program?如何使用C程序获取机器的MAC地址?
“我正在使用Ubuntu。我如何获得我的机器的MAC地址或使用C程序的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";
}
这是与Mozilla Chromeless,它使用Firefox的新JCTYPES像this使用。
基本上,我希望做这样的事情(从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;
}
非常感谢。这很好用! – 2011-05-19 00:27:18