依赖函数:
if_nametoindex IF名字 to IF索引
if_indextoname IF索引 to IF名字
MACOS 10.7 版本支援(就是2011年发不OSX的第一个面向用的系统版本)
cpp
int GetInterfaceIndex(const ppp::string& ifrName) noexcept
{
if (ifrName.empty())
{
return -1;
}
int interface_index = (int)if_nametoindex(ifrName.data());
if (interface_index == 0 || interface_index == -1)
{
return -1;
}
return interface_index;
}
bool GetInterfaceName(int interface_index, ppp::string& ifrName) noexcept
{
ifrName.clear();
if (interface_index == 0 || interface_index == -1)
{
return false;
}
char buf[255];
if (if_indextoname((unsigned int)interface_index, buf))
{
char ch = *buf;
if (ch == '\x0')
{
return false;
}
ifrName = buf;
return true;
}
else
{
return false;
}
}