2011-05-18 33 views
3

此问题与此问题完全相同: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; 
} 

回答

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); 
} 
+0

非常感谢。这很好用! – 2011-05-19 00:27:18

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

这看起来再好,你可能会考虑的memcpy(MAC,s.ifr_addr.sa_data ,6)而不是你的循环。 – jedwards 2011-05-19 00:22:09

+1

这不仅仅是返回1还是0?我需要将地址作为字符串返回。 – 2011-05-19 13:56:03

+0

你需要MAC地址,它不只是字符串,它恰好是6个字节。成功返回值为0,否则返回1。函数参数是您在外部分配的输出缓冲区(最可能是静态的)。 – 2011-05-20 22:57:53

相关问题