繁体   English   中英

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

[英]How to get mac address for an interface in linux using a C Program?

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

通过谷歌搜索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;
}    

有一个很棒的图书馆来管理以太网。 如果你想要去低级别的东西,它当然值得学习。 学习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和win端口。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM