/*! \fn ILibGetLocalIPAddressList(int** pp_int)
\brief Gets a list of IP Addresses
\para
\b NOTE: \a pp_int must be freed
\param[out] pp_int Array of IP Addresses
\returns Number of IP Addresses returned
*/ int ILibGetLocalIPAddressList(int** pp_int) { // Posix will also use an Ioctl call to get the IPAddress List
//
char szBuffer[16*sizeof(struct ifreq)];/*stevens: 一个host最多有16个网卡接口*/ struct ifconf ifConf; struct ifreq ifReq; int nResult; int LocalSock; structsockaddr_in LocalAddr; int tempresults[16]; int ctr=0; int i; /* Create an unbound datagram socket to do the SIOCGIFADDR ioctl on. */ if((LocalSock =socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP))< 0) {
DEBUGSTATEMENT(printf("Can't do that\r\n")); exit(1); } /* Get the interface configuration information... */
ifConf.ifc_len =sizeof szBuffer;
ifConf.ifc_ifcu.ifcu_buf =(caddr_t)szBuffer;/*stevens:caddr_t就是void* */
nResult = ioctl(LocalSock,SIOCGIFCONF,&ifConf); if(nResult < 0) {
DEBUGSTATEMENT(printf("ioctl error\r\n")); exit(1); } /* Cycle through the list of interfaces looking for IP addresses. */ for(i = 0;(i < ifConf.ifc_len);)/*stevens: 遍历取得的ip接口信息*/ { struct ifreq *pifReq =(struct ifreq *)((caddr_t)ifConf.ifc_req + i);
i +=sizeof*pifReq; /* See if this is the sort of interface we want to deal with. */ strcpy(ifReq.ifr_name, pifReq -> ifr_name); if(ioctl (LocalSock,SIOCGIFFLAGS,&ifReq)< 0)/* stevens: 在kernel中,#define ifr_flags ifr_ifru.ifru_flags*/ {
DEBUGSTATEMENT(printf("Can't get flags\r\n")); exit(1); } /* Skip loopback, point-to-point and down interfaces, */ /* except don't skip down interfaces */ /* if we're trying to get a list of configurable interfaces. */ if((ifReq.ifr_flags & IFF_LOOPBACK)||(!(ifReq.ifr_flags & IFF_UP))) { continue; } if(pifReq -> ifr_addr.sa_family ==AF_INET) { /* Get a pointer to the address... */ memcpy(&LocalAddr,&pifReq -> ifr_addr,sizeof pifReq -> ifr_addr); if(LocalAddr.sin_addr.s_addr !=htonl(INADDR_LOOPBACK))/*stevens: 前面已经判断了*/ {/*if ((ifReq.ifr_flags & IFF_LOOPBACK) || (!(ifReq.ifr_flags & IFF_UP))), 为什么这里还要判断呢?*/
tempresults[ctr]= LocalAddr.sin_addr.s_addr; ++ctr; } } } close(LocalSock); *pp_int =(int*)malloc(sizeof(int)*(ctr)); memcpy(*pp_int,tempresults,sizeof(int)*ctr);/*stevens:返回值放最多16个IP*/ return(ctr); }