小编典典

如何使用C程序在linux中获取接口的mac地址?

linux

我想在Linux中使用C程序找到mac地址。怎么做?


阅读 398

收藏
2020-06-07

共1个答案

小编典典

通过Google搜索1分钟:(我自己尚未对其进行测试,此刻我正在Windows机器上工作)

/*
 * gethwaddr.c
 *
 * Demonstrates retrieving hardware address of adapter using ioctl()
 *
 * Author: Ben Menking <bmenking@highstream.net>
 *
 */
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>    
#include <sys/socket.h>
#include <net/if.h>

int main( int argc, char *argv[] )
{
    int s;
    struct ifreq buffer;

    s = socket(PF_INET, SOCK_DGRAM, 0);

    memset(&buffer, 0x00, sizeof(buffer));

    strcpy(buffer.ifr_name, "eth0");

    ioctl(s, SIOCGIFHWADDR, &buffer);

    close(s);

    for( s = 0; s < 6; s++ )
    {
        printf("%.2X ", (unsigned char)buffer.ifr_hwaddr.sa_data[s]);
    }

    printf("\n");

    return 0;
}
2020-06-07