c - ifreq's ifr_names are incorrect? -
the following function determines if given string valid network device name.
int isvalidndevice(char *name) { char data[4096]; struct ifconf ifc; struct ifreq *ifr; int sk; int nintfcs; sk = socket(af_inet, sock_dgram, 0); if(sk < 0) { perror("socket"); return 0; } ifc.ifc_len = sizeof(data); ifc.ifc_buf = (caddr_t)data; if(ioctl(sk, siocgifconf, &ifc) < 0) { perror("ioctl(siocgifconf)"); return 0; } ifr = (struct ifreq*)data; nintfcs = ifc.ifc_len / sizeof(struct ifreq); for(int i=0; < nintfcs; i++) { safe_printf("%s\n", (&ifr[i])->ifr_name); if (!strcmp((&ifr[i])->ifr_name, name)) { return 1; } } return 0; }
when run function, receive following output.
lo0
stf0
�2�>s
en1j
0
this code worked fine few months ago. has changed? doing incorrectly?
os: osx el capitan
the array of structures returned siocgifconf
ioctl not of same size in osx. have field ifr->ifr_addr.sa_len
which different each structure
modified function take care of this. hope helps:
int isvalidndevice(char *name) { char data[4096]; struct ifconf ifc; struct ifreq *ifr; int sk,length; sk = socket(af_inet, sock_dgram, 0); if(sk < 0) { perror("socket"); return 0; } ifc.ifc_len = sizeof(data); ifc.ifc_buf = (caddr_t)data; if(ioctl(sk, siocgifconf, &ifc) < 0) { perror("ioctl(siocgifconf)"); return 0; } ifr = (struct ifreq*)data; for(int i=0;i<ifc.ifc_len;) { length=ifnamsiz + ifr->ifr_addr.sa_len; printf("%s\n", ifr->ifr_name); if (!strcmp(ifr->ifr_name,name)) { printf("interface found!\n"); return 1; } ifr=(struct ifr*)((char*)ifr+length); i+=length; } return 0; }
Comments
Post a Comment