C语言 想要获取系统上所有可用接口的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5989990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Want to get the list all the available interfaces on the system
提问by Onuralp
I want to get the list all the available interfaces on a particular PC along with their types that is wired or wireless. Currently I am doing the following but no success:-
我想获取特定 PC 上所有可用接口的列表以及它们的有线或无线类型。目前我正在执行以下操作但没有成功:-
ioctl(sd, SIOCGIFNAME, &ifr);
strncpy(ifname,ifr.ifr_name,IFNAMSIZ);
printf("Interface name :%s\n",ifname);
It will also be good if only names are available.
如果只有名称可用,这也很好。
回答by Wes Hardaker
If you're on ubuntu, as your tags indicate, you can always read /proc/net/devwhich has the information you're looking for in it.
如果您使用的是 ubuntu,正如您的标签所示,您始终可以阅读/proc/net/dev其中包含您要查找的信息。
回答by Onuralp
ifconfig -a
for all you can see interfaces avalaible lists you don't need script for C code for this,
对于所有你可以看到的接口可用列表,你不需要 C 代码的脚本,
?f you wanna more information for your interfaces
?如果你想了解更多关于你的界面的信息
lspci
You can find your interfaces type and models
您可以找到您的接口类型和型号
回答by Alexis Wilke
The C interface is called ifaddrs, you may include it with:
C 接口称为ifaddrs,您可以将其包含在:
#include <sys/types.h>
#include <ifaddrs.h>
The functions you are interested in are getifaddrsand once done with the data, freeifaddrs.
您感兴趣的功能是getifaddrs并且一旦完成数据,freeifaddrs.
struct ifaddrs {
struct ifaddrs *ifa_next; /* Next item in list */
char *ifa_name; /* Name of interface */
unsigned int ifa_flags; /* Flags from SIOCGIFFLAGS */
struct sockaddr *ifa_addr; /* Address of interface */
struct sockaddr *ifa_netmask; /* Netmask of interface */
union {
struct sockaddr *ifu_broadaddr;
/* Broadcast address of interface */
struct sockaddr *ifu_dstaddr;
/* Point-to-point destination address */
} ifa_ifu;
#define ifa_broadaddr ifa_ifu.ifu_broadaddr
#define ifa_dstaddr ifa_ifu.ifu_dstaddr
void *ifa_data; /* Address-specific data */
};
This structure includes all the info as the ifconfigcommand line tool returns.
此结构包含ifconfig命令行工具返回的所有信息。
For C++ users, I suggest you use a deleter like this:
对于 C++ 用户,我建议你使用这样的删除器:
void ifaddrs_deleter(struct ifaddrs * ia)
{
freeifaddrs(ia);
}
And attach the result of getifaddrs()to it with:
并将结果附加getifaddrs()到它:
struct ifaddrs * ifa_start(nullptr);
if(getifaddrs(&ifa_start) != 0)
{
return;
}
// will automatically delete on exception or any return
std::shared_ptr<struct ifaddrs> auto_free(ifa_start, ifaddrs_deleter);
回答by jai3232
I just use this command for Ubuntu. I am not sure if this work for other distribution.
我只是在 Ubuntu 上使用这个命令。我不确定这是否适用于其他发行版。
ls /sys/class/net

