Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

linux

i want to find the mac address using a C program in linux. how to do it?

like image 359
Rohit Banga Avatar asked Oct 05 '09 11:10

Rohit Banga


2 Answers

1 minute of searching throug google: (i haven't tested it myself, i'm working on a windows machine in the moment)

/*
 * 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;
}    
like image 198
nuriaion Avatar answered Nov 15 '22 11:11

nuriaion


There is a great library to manage ethernet. If You want go to low level stuff its certainly worth to learn. It's quite hard C API to learn.

Lib PCAP.

link to lib pcap sourceforge

Some sample code:

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

}
}

There's also nice "kernel functions wrapper" like library: DNET

which provides great functionality to use it on low level networking. (also getting MAC addresses).

DNET

There are UNIX & win ports for both libraries.

like image 37
bua Avatar answered Nov 15 '22 11:11

bua