1. 通过网络设备名获取网络设备id(if_index)
-
/*
-
*return val:
-
* -1 : fail
-
* others : interface index
-
*/
-
short get_ifindex_by_name(const char * name)
-
{
-
struct ifreq ifr;
-
int sockfd = -1;
-
int err = -1;
-
-
if (!name){
-
return -1;
-
}
-
-
/*create socket*/
-
sockfd = socket(PF_INET, SOCK_DGRAM, 0);
-
if (sockfd <= 0){
-
return -1;
-
}
-
-
/*get if index by calling ioctl*/
-
strncpy(ifr.ifr_name, name, IFNAMSIZ);
-
err = ioctl(sockfd, SIOCGIFINDEX, (void *) &ifr);
-
if (err == -1){
-
return -1;
-
}
-
-
return ifr.ifr_ifindex;
-
}
2. 通过网络设备名获取网络设备MAC地址
-
char *get_mac(char * ifname, char * mac)
-
{
-
struct ifreq ifreq;
-
unsigned char *p = NULL;
-
int sock = -1;
-
-
if(ifname == NULL || mac == NULL){
-
printf("get mac character ERROR!");
-
return NULL;
-
}
-
-
if((sock=socket(AF_INET,SOCK_STREAM,0))<0){
-
perror("socket");
-
return NULL;
-
}
-
-
strcpy(ifreq.ifr_name,ifname);
-
if(ioctl(sock,SIOCGIFHWADDR,&ifreq)<0){
-
perror("ioctl");
-
close(sock);
-
return NULL;
-
}
-
-
p = (unsigned char *)(ifreq.ifr_hwaddr.sa_data);
-
sprintf(mac,"%02x:%02x:%02x:%02x:%02x:%02x",
-
p[0], p[1], p[2], p[3], p[4], p[5]);
-
-
return mac;
-
}
3. 通过网络设备名获取网络设备ip地址:
-
int get_dev_ip(const char *ifname, char *ip_addr, int len)
-
{
-
struct ifreq ifr;
-
struct sockaddr_in *addr = NULL;
-
int sockfd = -1;
-
-
if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0){
-
perror("socket");
-
return -1;
-
}
-
-
memset(&ifr, 0, sizeof(struct ifreq));
-
addr = (struct sockaddr_in *)&ifr.ifr_addr;
-
addr->sin_family = AF_INET;
-
strcpy(ifr.ifr_name,ifname);
-
-
if (ioctl(sockfd, SIOCGIFADDR, &ifr) == 0) {
-
snprintf(ip_addr, len, "%s", inet_ntoa(addr->sin_addr));
-
close(sockfd);
-
return 0;
-
}
-
-
close(sockfd);
-
return -1;
-
}
阅读(1677) | 评论(0) | 转发(0) |