在自定义 C/C++ 程序中获取 PPP0 接口 Tx/Rx 字节的最简单方法是什么?
What is the easiest way to get PPP0 interface Tx/Rx bytes in a custom C/C++ program?
我需要在我的 C/C++ 程序 Tx/Rx 中显示有关三个网络接口的信息。其中之一是 ppp 接口,但我的代码不适用于 ppp0。
我正在使用 getifaddrs 手册页中的代码示例(参见 man getifaddrs),它主要检查接口是否具有 AF_PACKET 系列,如果是,则检索 Tx/Rx 来自 ifaddrs 结构的 ifa->ifa_data 成员的信息。但是此代码对于 ppp0 接口失败。在网上搜索了一下,找到了pppstats的源码,但是看着代码有点繁琐,因为里面有很多ifdefs,用于条件代码编译。我看到必须使用 ioctl,但我不知道具体如何使用。
在 linux 系统中从 ppp0 获取 Tx/Rx 字节信息的最简单代码是什么?真的需要使用 ioctl 吗?
提前致谢
我目前处于同样的情况,今天花了一些时间研究和编码这个问题。我也是从查看 pppstats
源代码开始的。
What would be the simplest code to get the Tx/Rx bytes information from ppp0 in a linux system ? Is it really needed to use ioctl ?
虽然我无法真正回答您的确切问题,但这是我最终读取 ppp0 接口上的 RX/TX 字节的 (c++) 代码:
#include <linux/if_ppp.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
{
auto sockfd = ::socket(PF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
std::cout << "couldn't open socket : " << errno << std::endl;
return;
}
ifreq req {};
ppp_stats stats {};
req.ifr_data = reinterpret_cast<caddr_t>(&stats);
::strncpy(&req.ifr_name[0], "ppp0", sizeof(req.ifr_name));
auto ret = ::ioctl(sockfd, SIOCGPPPSTATS, &req);
if (ret < 0) {
std::cout << "couldn't get PPP statistics : " << errno << std::endl;
} else {
std::cout << "received bytes : " << stats.p.ppp_ibytes << std::endl;
std::cout << "sent bytes : " << stats.p.ppp_obytes << std::endl;
}
auto ret = ::close(sockfd);
if (ret != 0) {
std::cout << "couldn't close socket : " << errno << std::endl;
}
}
我需要在我的 C/C++ 程序 Tx/Rx 中显示有关三个网络接口的信息。其中之一是 ppp 接口,但我的代码不适用于 ppp0。
我正在使用 getifaddrs 手册页中的代码示例(参见 man getifaddrs),它主要检查接口是否具有 AF_PACKET 系列,如果是,则检索 Tx/Rx 来自 ifaddrs 结构的 ifa->ifa_data 成员的信息。但是此代码对于 ppp0 接口失败。在网上搜索了一下,找到了pppstats的源码,但是看着代码有点繁琐,因为里面有很多ifdefs,用于条件代码编译。我看到必须使用 ioctl,但我不知道具体如何使用。
在 linux 系统中从 ppp0 获取 Tx/Rx 字节信息的最简单代码是什么?真的需要使用 ioctl 吗?
提前致谢
我目前处于同样的情况,今天花了一些时间研究和编码这个问题。我也是从查看 pppstats
源代码开始的。
What would be the simplest code to get the Tx/Rx bytes information from ppp0 in a linux system ? Is it really needed to use ioctl ?
虽然我无法真正回答您的确切问题,但这是我最终读取 ppp0 接口上的 RX/TX 字节的 (c++) 代码:
#include <linux/if_ppp.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <unistd.h>
{
auto sockfd = ::socket(PF_INET, SOCK_DGRAM, 0);
if (sockfd < 0) {
std::cout << "couldn't open socket : " << errno << std::endl;
return;
}
ifreq req {};
ppp_stats stats {};
req.ifr_data = reinterpret_cast<caddr_t>(&stats);
::strncpy(&req.ifr_name[0], "ppp0", sizeof(req.ifr_name));
auto ret = ::ioctl(sockfd, SIOCGPPPSTATS, &req);
if (ret < 0) {
std::cout << "couldn't get PPP statistics : " << errno << std::endl;
} else {
std::cout << "received bytes : " << stats.p.ppp_ibytes << std::endl;
std::cout << "sent bytes : " << stats.p.ppp_obytes << std::endl;
}
auto ret = ::close(sockfd);
if (ret != 0) {
std::cout << "couldn't close socket : " << errno << std::endl;
}
}