![ContractedBlock.gif](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![ExpandedBlockStart.gif](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
BOOL GetNicInfoForLinux()
{
int skfd = -1, if_cnt = 0, if_idx = 0;;
struct ifreq if_buf[MAX_NET_CARDS];
struct ifconf ifc;
u_int8_t mac_addr[MAC_ADDR_LEN];
u_int32_t ip = 0, netmask = 0;
if_name_index_t if_name_index;
BOOL ip_get = FALSE, netmask_get = FALSE;
struct list_head *ip_info_list = NULL;
if ((skfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
LogError("Get NIC info, Create socket error");
return FALSE;
}
ifc.ifc_len = sizeof(if_buf);
ifc.ifc_buf = (char *)if_buf;
if (!ioctl(skfd, SIOCGIFCONF, (char *)&ifc))
{
if_cnt = (ifc.ifc_len) / (sizeof(struct ifreq));
for (if_idx = 0; if_idx < if_cnt; ++if_idx)
{
/* ignore local loopback interface */
if (STRCMP(LOOPBACK_IF_NAME, if_buf[if_idx].ifr_name) == 0)
continue;
/* copy NIC name */
MEMSET(&if_name_index, 0, sizeof(if_name_index_t));
STRCPY(if_name_index.if_name, if_buf[if_idx].ifr_name);
/* get interface flags */
if (!(ioctl(skfd, SIOCGIFFLAGS, (char *)(&if_buf[if_idx]))))
{
/* this interface is up and running */
if ((if_buf[if_idx].ifr_flags & IFF_UP) &&
(if_buf[if_idx].ifr_flags & IFF_RUNNING))
{
if (!(ioctl(skfd, SIOCGIFHWADDR, (char *)(&if_buf[if_idx]))))
{
MEMCPY(mac_addr, (char *)(&(if_buf[if_idx].ifr_hwaddr.sa_data)), MAC_ADDR_LEN);
/* add new NIC */
ip_info_list = AddNicToNewNicInfoList(mac_addr, MAC_ADDR_LEN, &if_name_index, &g_newNicInfoList);
}
/* get ip address of this NIC */
if (!(ioctl(skfd, SIOCGIFADDR, (char *)(&if_buf[if_idx]))))
{
ip = ((struct sockaddr_in *)(&(if_buf[if_idx].ifr_addr)))->sin_addr.s_addr;
ip_get = TRUE;
}
/* get ip netmask */
if (!(ioctl(skfd, SIOCGIFNETMASK, (char *)(&if_buf[if_idx]))))
{
netmask = ((struct sockaddr_in *)(&(if_buf[if_idx].ifr_netmask)))->sin_addr.s_addr;
netmask_get = TRUE;
}
/* insert ip to ip list */
if ((TRUE == ip_get) && (TRUE == netmask_get))
{
AddIpToIpList(ip, netmask, ip_info_list);
ip_get = FALSE;
netmask_get = FALSE;
}
}
}
} /* end of for (if_idx = 0; if_idx < if_cnt; ++if_idx) */
}
close(skfd);
return TRUE;