Last active
August 4, 2017 17:31
-
-
Save cedriczirtacic/e631a8e7facbf725659ba667ad3e6642 to your computer and use it in GitHub Desktop.
using ioctl(2) to get the original hwaddr of a network interface
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// gcc -o get_orig_hwaddr get_orig_hwaddr.c | |
#include <stdio.h> | |
#include <errno.h> | |
#include <string.h> | |
#include <net/if.h> | |
#include <sys/ioctl.h> | |
#include <sys/socket.h> | |
char *get_addr (int fd, struct ifreq *ifrq) { | |
char *hwaddr; | |
if ((ioctl(fd, SIOCGIFHWADDR, ifrq)) == -1){ | |
perror("[-] error"); | |
return NULL; | |
} | |
hwaddr = ifrq->ifr_ifru.ifru_hwaddr.sa_data; | |
return (hwaddr); | |
} | |
int main(int argc, char *argv[]) { | |
int nlsock; | |
if (argc > 2 || ( argc == 2 && (strcmp(argv[1],"-h")) == 0 ) ) { | |
fprintf(stderr, "usage: %s [-h] <ifdev>\n", argv[0]); | |
return 1; | |
} | |
nlsock = socket(AF_UNIX, SOCK_RAW, 0); | |
if( argc == 2 ){ | |
struct ifreq ifr; | |
strncpy(ifr.ifr_name, argv[1], IF_NAMESIZE-1); | |
char *mac = get_addr(nlsock, &ifr); | |
if (mac == NULL) | |
return errno; | |
for(int i=0; i<6;i++){ | |
printf("%02x", mac[i]); | |
if ( i < 5 ) | |
printf(":"); | |
} | |
printf("\n"); | |
} else { | |
struct if_nameindex *ifindex = if_nameindex(); | |
while(ifindex->if_index > 0){ | |
struct ifreq ifr; | |
strncpy(ifr.ifr_name, ifindex->if_name, IF_NAMESIZE-1); | |
char *mac = get_addr(nlsock, &ifr); | |
if (mac == NULL) | |
return errno; | |
for(int i=0; i<6;i++){ | |
printf("%02x", mac[i]); | |
if ( i < 5 ) | |
printf(":"); | |
} | |
printf(" (%s)\n", ifindex->if_name); | |
ifindex++; | |
} | |
} | |
shutdown(nlsock, SHUT_RD); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment