获取本地IP及Mac地址
时间:2010-05-26 来源:Leanx
#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>
#define ETH_NAME "eth0"
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);
printf("IP: %s \n", value);
break;
case 2: //ipmask
if (ioctl(inet_sock, SIOCGIFNETMASK, &ifr)< 0)
{
perror("ioctl");
}
value = inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr);
printf("IPMask: %s \n", value);
break;
case 3: //mac
if (ioctl(inet_sock, SIOCGIFHWADDR, &ifr)< 0)
{
perror("ioctl");
}
ptr = &ifr.ifr_ifru.ifru_hwaddr.sa_data[0];
printf("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 *ip, *ipmask, *mac;
ip = get_interface(ETH_NAME, 1);
ipmask = get_interface(ETH_NAME, 2);
mac = get_interface(ETH_NAME, 3);
}
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define ETH_NAME "eth0"
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);
printf("IP: %s \n", value);
break;
case 2: //ipmask
if (ioctl(inet_sock, SIOCGIFNETMASK, &ifr)< 0)
{
perror("ioctl");
}
value = inet_ntoa(((struct sockaddr_in*)&(ifr.ifr_addr))->sin_addr);
printf("IPMask: %s \n", value);
break;
case 3: //mac
if (ioctl(inet_sock, SIOCGIFHWADDR, &ifr)< 0)
{
perror("ioctl");
}
ptr = &ifr.ifr_ifru.ifru_hwaddr.sa_data[0];
printf("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 *ip, *ipmask, *mac;
ip = get_interface(ETH_NAME, 1);
ipmask = get_interface(ETH_NAME, 2);
mac = get_interface(ETH_NAME, 3);
}
相关阅读 更多 +