Skip to content

Instantly share code, notes, and snippets.

@r4um
Created April 18, 2012 14:14
Show Gist options
  • Save r4um/2413867 to your computer and use it in GitHub Desktop.
Save r4um/2413867 to your computer and use it in GitHub Desktop.
fetch if addr
#include <unistd.h>
#include <net/if.h>
#include <netinet/if_ether.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
struct if_info {
char if_name[IFNAMSIZ];
u_int8_t ipaddr[4];
u_int8_t hwaddr[ETH_ALEN];
};
void fill_if_info(const char* if_name,struct if_info* ifr_info)
{
int s;
struct ifreq ifr;
struct sockaddr_in *saddr;
/* copy the interface name */
strcpy(ifr_info->if_name,if_name);
/* create a socket for ioctl operations */
s = socket(AF_INET,SOCK_STREAM,0);
/* copy the interface name to ifreq.if_name */
strcpy(ifr.ifr_name, if_name);
/* do an ioctl to get ipaddress */
ioctl(s, SIOCGIFADDR, &ifr);
saddr = (struct sockaddr_in*) &ifr.ifr_addr;
memcpy(&ifr_info->ipaddr, &saddr->sin_addr, sizeof(ifr_info->ipaddr));
/* do an ioctl to get hardware address*/
ioctl(s, SIOCGIFHWADDR, &ifr);
memcpy(ifr_info->hwaddr, &ifr.ifr_hwaddr.sa_data, ETH_ALEN);
}
void print_if_info(struct if_info* a)
{
printf(" device: %s.\n", a->if_name);
printf(" ipaddr: %u.\n", a->ipaddr[0]);
printf(" hwaddr: %02x:%02x:%02x:%02x:%02x:%02x.\n",a->hwaddr[0],
a->hwaddr[1],
a->hwaddr[2],
a->hwaddr[3],
a->hwaddr[4],
a->hwaddr[5]);
}
int main(int argc, char *argv[])
{
struct if_info a;
if(argc != 2) return 1;
fill_if_info(argv[1],&a);
print_if_info(&a);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment