2009-10-05 49 views

回答

26

每分鐘:(我還沒有測試它自己,我的工作在Windows機器上的那一刻)

/* 
* gethwaddr.c 
* 
* Demonstrates retrieving hardware address of adapter using ioctl() 
* 
* Author: Ben Menking <[email protected]> 
* 
*/ 
#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; 
}  
+0

無論如何得到它沒有硬編碼「eth0」?? – 2013-06-25 09:12:00

+0

你必須分配一個網絡適配器,否則沒有MAC地址,你可以通過輸入或參數來實現,但你需要一個適配器。 – 2014-12-03 23:22:19

+0

#include for close() – notlesh 2015-04-01 18:18:10

2

有一個偉大的圖書館管理以太網。 如果你想要去低層次的東西,它肯定值得學習。 學習C API非常困難。

Lib PCAP。

link to 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 &勝利端口。