1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| #include "protocol.h"
int get_info(struct nic_info *nic_info, char *if_name) { int sock, i, num=30; struct ifconf if_conf; struct ifreq *ifr; struct sockaddr_in *addr;
if((sock = socket(PF_INET, SOCK_STREAM,0)) < 0) { perror("socket "); return -1; }
memset(&if_conf, 0, sizeof(if_conf)); if_conf.ifc_len = sizeof(struct ifreq) * num; if_conf.ifc_buf = (__caddr_t)malloc(if_conf.ifc_len); memset(if_conf.ifc_buf, 0, sizeof(if_conf.ifc_len));
if(ioctl(sock, SIOCGIFCONF, (char *)&if_conf) < 0) { perror("ioctl() - get conf "); free(if_conf.ifc_buf); close(sock); return -1; }
for(ifr = if_conf.ifc_req; ifr->ifr_name[0]; ifr++) { if(!strcmp(ifr->ifr_name, if_name)) { addr = (struct sockaddr_in*)&ifr->ifr_addr; nic_info->in_addr.s_addr = addr->sin_addr.s_addr;
if(ntohl(nic_info->in_addr.s_addr) != INADDR_LOOPBACK) { if(ioctl(sock, SIOCGIFHWADDR, (char*)ifr) < 0) { perror("ioctl() - get mac address "); free(if_conf.ifc_buf); close(sock); return -1; } memcpy(nic_info->my_mac, ifr->ifr_hwaddr.sa_data, 6); }
if(ioctl(sock, SIOCGIFINDEX, (char*)ifr) < 0) { perror("ioctl() - get ifindex "); free(if_conf.ifc_buf); close(sock); return -1; } nic_info->ifindex = ifr->ifr_ifindex;
if(ioctl(sock, SIOCGIFBRDADDR, (char*)ifr) < 0) { perror("ioctl() - get broadcast addr "); free(if_conf.ifc_buf); close(sock); return -1; } addr = (struct sockaddr_in*)&ifr->ifr_broadaddr; nic_info->broadaddr.s_addr = addr->sin_addr.s_addr;
if(ioctl(sock, SIOCGIFNETMASK, (char *)ifr) < 0) { perror("ioctl() - get ifindex "); free(if_conf.ifc_buf); close(sock); return -1; } addr = (struct sockaddr_in*)&ifr->ifr_addr; nic_info->maskaddr.s_addr = addr->sin_addr.s_addr;
free(if_conf.ifc_buf); close(sock); return 0; } } free(if_conf.ifc_buf); close(sock); return -1; }
|