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

6
我想在Linux中使用C程序查找MAC地址。怎么做?
2个回答

29

在谷歌上搜索一分钟:(我自己没有测试过,我现在正在使用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;
}    

有没有办法在不硬编码“eth0”的情况下获取它? - Stefano Mtangoo
你必须分配一个网络适配器,否则就没有 MAC 地址,你可以通过输入或作为参数来完成,但你需要一个适配器。 - Michiel D

2

有一个很好的库可以管理以太网。如果你想要接触底层技术,学习它一定是值得的。但是它的 C API 非常难学。

Lib PCAP。

lib pcap sourceforge 链接

一些示例代码:

#include <pcap.h>
#include <stdlib.h>
#include <netinet/ip.h>
#include <netinet/if_ether.h>

void find_eth_addr(struct in_addr *search_ip, const struct pcap_pkthdr* pkthdr, const u_char *packet) {
struct ether_header *eth_hdr = (struct ether_header *)packet;

if (ntohs(eth_hdr->ether_type) == ETHERTYPE_IP) {
    struct ip *ip_hdr = (struct ip *)(packet + sizeof(struct ether_header));
if (ip_hdr->ip_dst.s_addr == search_ip->s_addr)
    print_eth_addr(eth_hdr->ether_dhost);
if (ip_hdr->ip_src.s_addr == search_ip->s_addr)
    print_eth_addr(eth_hdr->ether_shost);

}
}

还有一个很好的“内核函数包装器”类库: DNET

它提供了在低级网络上使用它的强大功能。 (也可以获取MAC地址)。

DNET

这两个库都有UNIX和Windows端口。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接