现代c++获取linux所有的网络接口名称
前言
本文介绍一种使用c++获取本地所有网络接口名称的方法。
一、在linux中查看网络接口名称
在linux
系统中可以使用ifconfig -a
命令列举出本机所有网络接口。如下图所示
也可以使用ip a
命令,如下图所示
二、使用c++代码获取
需要包含<ifaddrs.h>
,<sys/types.h>
头文件
写下如下图代码
cpp
#include <string>
#include <sys/types.h>
#include <vector>
#include <ifaddrs.h>
std::vector<std::string> interfaceNames() {
std::vector<std::string> names;
struct ifaddrs *ifaddr{nullptr};
if (getifaddrs(&ifaddr) == 0) {
for (auto ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr->sa_family == AF_PACKET) {
names.push_back(ifa->ifa_name);
}
}
freeifaddrs(ifaddr);
}
return names;
}
为了打印方便,我们重载一下左移运算符
cpp
std::ostream &operator<<(std::ostream &os, const std::vector<std::string> &v) {
os << "[";
for (auto &s : v) {
os << s;
if (&s != &v.back()) {
os << ",";
}
}
return os << "]";
}
三、验证
在main.cpp
的main
函数中写下如下代码
cpp
int main(int argc, char **argv) {
std::cout << interfaceNames() << std::endl;
return 0;
}
编译并验证,g++ main.cpp -o main && ./main
,结果如下
确实可以获取到接口名称。
四、完整代码如下
cpp
#include <ifaddrs.h>
#include <iostream>
#include <string>
#include <sys/types.h>
#include <vector>
std::vector<std::string> interfaceNames() {
std::vector<std::string> names;
struct ifaddrs *ifaddr{nullptr};
if (getifaddrs(&ifaddr) == 0) {
for (auto ifa = ifaddr; ifa; ifa = ifa->ifa_next) {
if (ifa->ifa_addr->sa_family == AF_PACKET) {
names.push_back(ifa->ifa_name);
}
}
freeifaddrs(ifaddr);
}
return names;
}
std::ostream &operator<<(std::ostream &os, const std::vector<std::string> &v) {
os << "[";
for (auto &s : v) {
os << s;
if (&s != &v.back()) {
os << ",";
}
}
return os << "]";
}
int main(int argc, char **argv) {
std::cout << interfaceNames() << std::endl;
return 0;
}
五、总结
本文介绍了一种使用c++获取本地所有网络接口的方法,亲测可用!!!