我有一个很好的小程序,它为我提供了一个系统连接到的网络上所有活动IP的矢量…但只能在Windows上工作
std::vector<std::string> resultIPList;
PMIB_IPNET_TABLE2 pipTable = NULL;
unsigned long status = GetIpNetTable2(AF_INET, &pipTable);
if(status != NO_ERROR)
{
LOG_ERROR("Error in getting ip Table")
return resultIPList;
}
for(unsigned i = 0; i < pipTable->NumEntries; i++)
{
char* ip = inet_ntoa(pipTable->Table[i].Address.Ipv4.sin_addr);
std::string str = std::string(ip);
resultIPList.push_back(str);
}
FreeMibTable(pipTable);
pipTable = NULL;
return resultIPList;
在Linux中有没有什么方法可以做到这一点(替换getipnettable函数)。我在用RHEL
最佳答案
字面意义:ftw
#include <ifaddrs.h>
#include <net/if.h>
#include <netinet/in.h>
#include <cstdlib>
ifaddrs* pAdapter = NULL;
ifaddrs* pList = NULL;
int result = getifaddrs(&pList);
if (result == -1)
return;
pAdapter = pList;
while (pAdapter)
{
if ((pAdapter->ifa_addr != NULL) && (pAdapter->ifa_flags & IFF_UP))
{
if (pAdapter->ifa_addr->sa_family == AF_INET)
{
sockaddr_in* addr = (sockaddr_in*)(pAdapter->ifa_addr);
}
else if (pAdapter->ifa_addr->sa_family == AF_INET6)
{
sockaddr_in6* addr6 = (sockaddr_in6*)(pAdapter->ifa_addr);
}
}
pAdapter = pAdapter->ifa_next;
}
freeifaddrs(pList);
pList = NULL;