I’m tasked with helping gather network data from Linux machines in C++. I’m new to C++, and need some advice. I need to take this shell script and simulate it as close as possible. Basically, I need to dump all the networking details of the machine – netstat or ss, ifconfig, etc.
Previous shell script snippet:
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
}
And this is what I’ve tried in C++ so far. It works, in creating the text files, but I feel like I’m shortcutting or not doing it efficiently. Any advice is appreciated.
#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
Answers
My advice is to use three important facts: 1) that Linux is open source, 2) most of it and its system calls are written in C, and 3) C can compile as C++.
So if you take for example your code above, if you want to do ifconfig more efficiently, start with what you have, and then replace the ifconfig code with parts of the original source which can be found here:
https://github.com/giftnuss/net-tools/blob/master/ifconfig.c
Take a look at the /proc file system.
However beware that it changes from Linux version to version.