Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用C程序在linux中获取接口的mac地址?_C_Linux - Fatal编程技术网

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

如何使用C程序在linux中获取接口的mac地址?,c,linux,C,Linux,我想在linux中使用C程序查找mac地址。如何做到这一点?通过谷歌搜索一分钟:(我自己还没有测试过,我现在正在windows机器上工作) /* *gethwaddr.c * *演示如何使用ioctl()检索适配器的硬件地址 * *作者:Ben Menking * */ #包括 #包括 #包括 #包括 #包括 int main(int argc,char*argv[]) { int-s; 结构ifreq缓冲区; s=插座(PF_INET,SOCK_DGRAM,0); memset(&buffer

我想在linux中使用C程序查找mac地址。如何做到这一点?

通过谷歌搜索一分钟:(我自己还没有测试过,我现在正在windows机器上工作)

/*
*gethwaddr.c
*
*演示如何使用ioctl()检索适配器的硬件地址
*
*作者:Ben Menking
*
*/
#包括
#包括
#包括
#包括
#包括
int main(int argc,char*argv[])
{
int-s;
结构ifreq缓冲区;
s=插座(PF_INET,SOCK_DGRAM,0);
memset(&buffer,0x00,sizeof(buffer));
strcpy(buffer.ifr_名称,“eth0”);
ioctl(s、SIOCGIFHWADDR和缓冲器);
关闭(s);;
对于(s=0;s<6;s++)
{
printf(“%.2X”,(无符号字符)缓冲区.ifr_hwaddr.sa_数据];
}
printf(“\n”);
返回0;
}    

有一个很好的管理以太网的库。 如果你想学习低级的东西,那当然值得学习。 学习C API相当困难

Lib-PCAP

一些示例代码:

#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);

}
}
#包括
#包括
#包括
#包括
void find_eth_addr(地址中的结构*search_ip,常量结构pcap\u pkthdr*pkthdr,常量字符*packet){
结构以太头*以太头hdr=(结构以太头*)数据包;
如果(ntohs(eth\U hdr->乙醚型)=乙醚型IP){
结构ip*ip_hdr=(结构ip*)(数据包+大小of(结构以太网头));
如果(ip_hdr->ip_dst.s_addr==搜索ip->s_addr)
打印电子邮件地址(电子邮件地址->电子邮件地址);
如果(ip_hdr->ip_src.s_addr==搜索\u ip->s_addr)
打印电子邮件地址(电子邮件地址->电子邮件地址);
}
}
还有很好的“内核函数包装器”,如库: DNET

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


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

无论如何,要在没有硬编码“eth0”的情况下获得它,您必须分配一个网络适配器,否则没有mac地址,您可以通过输入或作为参数来完成,但您需要一个适配器。
#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);

}
}