在C ++中获取Linux网络统计信息

时间:2020-05-15 01:43:56

标签: c++ linux

我的任务是帮助从C ++的Linux机器中收集网络数据。我是C ++的新手,需要一些建议。我需要使用此Shell脚本并对其进行尽可能接近的模拟。基本上,我需要转储计算机的所有网络详细信息-netstat或ss,ifconfig等。

先前的shell脚本代码段:

get_networkdata(){
    #All Active Network Connections
    {
        if netstat -pvWanoee &> /dev/null
        then
            # gnu
            netstat -pvWanoee
        elif netstat -pvTanoee &> /dev/null
    then
            # redhat/centos
            netstat -pvTanoee
    else
        netstat -anp
        fi
    } > "$SAVETO/netstat.txt"

    #Network Configuration
    {
        echo  -e "\n</etc/network/interfaces>";cat /etc/network/interfaces
        echo  -e "\n<ifconfig -a>";ifconfig -a
        echo  -e "\n</etc/resolv.conf>";cat /etc/resolv.conf
        echo  -e "\n<ip addr>"; ip addr
        echo  -e "\n<ip link>";ip link
        echo  -e "\n<netstat -anp>;"netstat -anp
        if lsof -i -n -P &> /dev/null
        then
            echo  -e "\n<lsof -i -n -P>";lsof -i -n -P
        fi
        echo  -e "\n<ss -ap>";ss -ap
        echo  -e "\n<route -n>";route -n # "netstat -nr"; "ip route"
        echo  -e "\n<ip neigh>";ip neigh
        echo  -e "\n</etc/hostname>";cat /etc/hostname
        echo  -e "\n<cat /etc/hosts>";cat /etc/hosts
        echo  -e "\n<cat /etc/hosts.allow>";cat /etc/hosts.allow
        echo  -e "\n<cat /etc/hosts.deny>";cat /etc/hosts.deny
    } > "$SAVETO/netinfo.txt"

    #SSH Folder Copy
    tar -zcvf "$SAVETO/ssh_folder.tar.gz" /etc/ssh/* 2> /dev/null
}

这是到目前为止我在C ++中尝试过的方法。它可以在创建文本文件时起作用,但是我感觉是捷径或效率不高。任何建议表示赞赏。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <string>

    using namespace std;

    string GetStdoutfromCommand(string cmd) {

        string data;
        FILE * stream;
        const int max_buffer = 256;
        char buffer[max_buffer];
        cmd.append (" 2>&1" );

        stream = popen(cmd.c_str(), "r");
        if (stream) {

            while (!feof(stream))
            if (fgets(buffer, max_buffer, stream) !=nullptr) data.append(buffer);
            pclose(stream);
        }

        return data;
    }

    int main () {

        string net_devices = GetStdoutfromCommand("ifconfig -a >network_devices.txt");
        string ss = GetStdoutfromCommand("ss -a -pl >netstats.txt");
        string ip_route = GetStdoutfromCommand("ip route >ip_route.txt");

        return 0;
    }

2 个答案:

答案 0 :(得分:1)

我的建议是使用三个重要事实:1)Linux是开源的,2)大多数Linux及其系统调用都是用C编写的,并且3)C可以编译为C ++。

因此,以上面的代码为例,如果您想更有效地执行ifconfig,请从已有的内容开始,然后将ifconfig代码替换为原始源代码的一部分,可以在这里找到:

https://github.com/giftnuss/net-tools/blob/master/ifconfig.c

答案 1 :(得分:0)

看看/ proc文件系统。 但是请注意,它会随Linux版本的变化而变化。