#include <string.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
char * get_interface(char *interface, int type)
{
int inet_sock;
char *value= NULL;
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
inet_sock = socket(AF_INET, SOCK_DGRAM, 0);
unsigned char *ptr;
strcpy(ifr.ifr_name, interface);
memset(&ifr.ifr_hwaddr, 0, sizeof(struct sockaddr));
switch (type)
{
case 1: //ip
if (ioctl(inet_sock, SIOCGIFADDR, &ifr)< 0)
{
perror("ioctl");
}
value = inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr);
break;
case 2: //ipmask
if (ioctl(inet_sock, SIOCGIFNETMASK, &ifr)< 0)
{
perror("ioctl");
}
value = inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr);
break;
case 3: //mac
if (ioctl(inet_sock, SIOCGIFHWADDR, &ifr)< 0)
{
perror("ioctl");
}
ptr = &ifr.ifr_ifru.ifru_hwaddr.sa_data[0];
printf("\nrequest mac%02X:%02X:%02X:%02X:%02X:%02X\n",*ptr,*(ptr+1),*(ptr+2),*(ptr+3),*(ptr+4),*(ptr+5));
printf ("ptr+3: %02x\n", ptr[3]);
break;
default:
break;
}
return value;
}
int main()
{
char *mac;
mac = get_interface("eth0",3);
}
|