用C++和shell获取本机CPU、网卡IO、内存、磁盘等的基本信息

用C++和shell获取本机CPU、网卡、内存、磁盘等的基本信息;

由于对C++相关的函数没多少了解,但是觉得用shell反而相对简单一些:

一、shell脚本,用来辅助C++获取主机的资源使用信息

(1) cpurate.sh 获取cpu的使用率

#!/bin/sh

##echo user nice system idle iowait irq softirq
CPULOG_1=$(cat /proc/stat | grep 'cpu ' | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
SYS_IDLE_1=$(echo $CPULOG_1 | awk '{print $4}')
Total_1=$(echo $CPULOG_1 | awk '{print $1+$2+$3+$4+$5+$6+$7}')

sleep 1

CPULOG_2=$(cat /proc/stat | grep 'cpu ' | awk '{print $2" "$3" "$4" "$5" "$6" "$7" "$8}')
SYS_IDLE_2=$(echo $CPULOG_2 | awk '{print $4}')
Total_2=$(echo $CPULOG_2 | awk '{print $1+$2+$3+$4+$5+$6+$7}')

SYS_IDLE=`expr $SYS_IDLE_2 - $SYS_IDLE_1`

Total=`expr $Total_2 - $Total_1`
SYS_USAGE=`expr $SYS_IDLE/$Total*100 |bc -l`

SYS_Rate=`expr 100-$SYS_USAGE |bc -l`

Disp_SYS_Rate=`expr "scale=3; a=$SYS_Rate/1;  if(length(a)==scale(a) && a!=0) print 0;print a" |bc`
echo $Disp_SYS_Rate%

(2)memrate.sh 获取内存的使用率

#!/bin/sh

MemTotal=$(cat /proc/meminfo | grep 'MemTotal' | awk '{print $2}')
MemFree=$(cat /proc/meminfo | grep 'MemFree' | awk '{print $2}')

Disp_SYS_Rate=`expr "scale=3; a=100*$MemFree/$MemTotal;  if(length(a)==scale(a)) print 0;print a" |bc`
echo $Disp_SYS_Rate%

(3)network.sh 获取网卡的使用率

#!/bin/sh

cat /proc/net/dev | grep 'eth' | awk '{ if($2!=0) print $1"/"$2}'

(4)getsize.sh 获取磁盘的可用与总共的大小

#!/bin/bash

LISTEN_PATH=./
if [ -n $1 ]; then
    LISTEN_PATH=$1
fi
echo `df -h $LISTEN_PATH | grep "dev" `| awk '{print $3"/"$2}'

二、C++ file用来调用上面的shell文件获取信息

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

using namespace std;

bool GetCpuRate(std::string& cpurate)
{
    FILE *file;
    string cmd("./cpurate.sh");

    file = popen(cmd.c_str(), "r");
    if(file == NULL)
    {
        cout<<cmd<<" fail"<<endl;
        return false;
    }
    char buf[512] = {0};

    while(fgets(buf, sizeof(buf), file) != NULL)
    {
        char tmpbuf[512]={0};
        sscanf(buf,"%s",tmpbuf);
        cpurate=std::string(tmpbuf);
    }
    pclose(file);
    return true;
}
bool GetMemRate(std::string& memrate)
{
    FILE *file;
    string cmd("./memrate.sh");

    file = popen(cmd.c_str(), "r");
    if(file == NULL)
    {
        cout<<cmd<<" fail"<<endl;
        return false;
    }
    char buf[512] = {0};

    while(fgets(buf, sizeof(buf), file) != NULL)
    {
        char tmpbuf[512]={0};
        sscanf(buf,"%s",tmpbuf);
        memrate=std::string(tmpbuf);
    }
    pclose(file);
    return true;
}

bool GetNetInfo(std::string& network)
{
    FILE *file;
    string cmd("./network.sh");

    file = popen(cmd.c_str(), "r");
    if(file == NULL)
    {
        cout<<cmd<<" fail"<<endl;
        return false;
    }
    char buf[512] = {0};

    while(fgets(buf, sizeof(buf), file) != NULL)
    {
        char tmpbuf[512]={0};
        sscanf(buf,"%s",tmpbuf);
        network=std::string(tmpbuf);
    }
    pclose(file);
    return true;
}

bool GetDiskInfo(std::string& diskInfo,const std::string path)
{
    FILE *file;
    string cmd("./getsize.sh "+path);

    file = popen(cmd.c_str(), "r");
    if(file == NULL)
    {
        cout<<cmd<<" fail"<<endl;
        return false;
    }
    char buf[512] = {0};

    while(fgets(buf, sizeof(buf), file) != NULL)
    {
        char tmpbuf[512]={0};
        sscanf(buf,"%s",tmpbuf);
        diskInfo=std::string(tmpbuf);
    }
    pclose(file);
    return true;
}

int main()
{
    std::string cpurate, memrate, network, diskInfo;
    GetCpuRate(cpurate);
    GetMemRate(memrate);
    GetNetInfo(network);
    GetDiskInfo(diskInfo, "/home/");
    cout<<cpurate<<endl;
    cout<<memrate<<endl;
    cout<<network<<endl;
    cout<<diskInfo<<endl;
    return 0;
}

三、获取当前活动的网卡和mac,C++file(这两个是抄别人的,但是时间有点久,找不到是谁的了)

(1) getethaddr.c 获取当前的网卡地址

#include <stdio.h>
#include <ifaddrs.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>

int get_local_ip(char *ip_list) {
        struct ifaddrs *ifAddrStruct;
        void *tmpAddrPtr;
        char ip[INET_ADDRSTRLEN];
        int n = 0;
        getifaddrs(&ifAddrStruct);
        while (ifAddrStruct != NULL) {
                if (ifAddrStruct->ifa_addr->sa_family==AF_INET) {
                        tmpAddrPtr=&((struct sockaddr_in *)ifAddrStruct->ifa_addr)->sin_addr;
                        inet_ntop(AF_INET, tmpAddrPtr, ip, INET_ADDRSTRLEN);
                        if (strcmp(ip, "127.0.0.1") != 0) {
//                              printf("%s IP Address:%s
", ifAddrStruct->ifa_name, ip);
                                if (n == 0){
                                        memcpy(ip_list, ip, INET_ADDRSTRLEN);
                                } else {
                                        memcpy(ip_list+INET_ADDRSTRLEN, ip, INET_ADDRSTRLEN);
                                }
                                n++;
                        }
                }
                ifAddrStruct=ifAddrStruct->ifa_next;
        }
        //free ifaddrs
        freeifaddrs(ifAddrStruct);
        return n;
}
int main()
{
        char ip[3][INET_ADDRSTRLEN];
        memset(ip, 0, sizeof(ip));
        int n;
        for (n=get_local_ip(*ip); n>0; n--) {
                printf("%s
", ip[n-1]);
        }
        return 0;
}

(2) 获取mac地址getmac.c 

#include <stdio.h> 
#include <fcntl.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 
  
#include <sys/ioctl.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <linux/if.h> 
  
#define IFNAMSIZ 16 

char ifname_buf[2048]; 
char *ifnames = ifname_buf; 
int count = 0; 
  
void add_interface_name(const char * name) 
{ 
    int i; 
    for (i=0;i<count;i++) 
    { 
        if (!strcmp(ifnames+i*IFNAMSIZ, name)) 
            return; 
    } 
    strncpy(ifnames+(count++)*IFNAMSIZ, name, IFNAMSIZ-1); 
} 
  
char * get_name(char *name, char *p) 
{ 
    while (isspace(*p)) 
    p++; 
    while (*p) { 
    if (isspace(*p)) 
        break; 
    if (*p == ':') {    /* could be an alias */
        char *dot = p, *dotname = name; 
        *name++ = *p++; 
        while (isdigit(*p)) 
        *name++ = *p++; 
        if (*p != ':') {    /* it wasn't, backup */
        p = dot; 
        name = dotname; 
        } 
        if (*p == '') 
        return NULL; 
        p++; 
        break; 
    } 
    *name++ = *p++; 
    } 
    *name++ = ''; 
    return p; 
} 
  
// get /proc/net/dev interface name list into buffer 
// return 0 if success 
int get_procnet_list() 
{ 
    FILE *fh; 
    char buf[512]; 
    fh = fopen("/proc/net/dev", "r"); 
    if (!fh) 
        return -1; 
  
    fgets(buf, sizeof buf, fh); /* eat title lines */
    fgets(buf, sizeof buf, fh); 
    while (fgets(buf, sizeof buf, fh)) 
    { 
        char name[IFNAMSIZ]; 
        get_name(name, buf); 
        add_interface_name(name); 
    } 
    fclose(fh); 
    return 0; 
} 
  
long mac_addr_sys ( u_char *addr) 
{ 
/* implementation for Linux */
    struct ifreq ifr; 
    struct ifreq *IFR; 
    struct ifconf ifc; 
    char buf[1024]; 
    int s, i; 
    int ok = 0; 
  
    // clear buffer 
    memset(ifname_buf, 0, sizeof(ifname_buf)); 
  
  
    s = socket(AF_INET, SOCK_DGRAM, 0); 
    if (s==-1) { 
        return -1; 
    } 
  
    ifc.ifc_len = sizeof(buf); 
    ifc.ifc_buf = buf; 
    ioctl(s, SIOCGIFCONF, &ifc); 
  
    IFR = ifc.ifc_req; 
    // put the ioctl interface names in the list 
    for (i = ifc.ifc_len / sizeof(struct ifreq); --i >= 0; IFR++) { 
            add_interface_name(IFR->ifr_name); 
    } 
    // put the /proc/net/dev interface names in the list 
    if (get_procnet_list()) 
        return -1; 
  
    // get the first mac address of eth* device hardware address 
    for (i = 0; i < count; i++) { 
        strcpy(ifr.ifr_name, ifnames + i*IFNAMSIZ); 
        if (!strncmp(ifr.ifr_name, "eth", 3)) 
            if (ioctl(s, SIOCGIFFLAGS, &ifr) == 0) { 
                if (! (ifr.ifr_flags & IFF_LOOPBACK)) { 
                    if (ioctl(s, SIOCGIFHWADDR, &ifr) == 0) { 
                        char *p = (char *)ifr.ifr_hwaddr.sa_data; 
                        if (!*((int *)p) && !*((int *)(p+2)) ) 
                            continue; 
                        // if not 00:00:00:00:00:00, yes, we get the real mac addr 
                        ok = 1; 
                        break; 
                    } 
                } 
            } 
    } 
  
    close(s); 
    if (ok) { 
        bcopy( ifr.ifr_hwaddr.sa_data, addr, 6); 
    } 
    else { 
        return -1; 
    } 
    return 0; 
} 
  

int main( int argc, char **argv) 
{ 
    long stat; 
    int i; 
    u_char addr[6]; 
  
    stat = mac_addr_sys( addr); 
    if (0 == stat) { 
        printf( "MAC address = "); 
        for (i=0; i<6; ++i) { 
            printf("%2.2x", addr[i]); 
            if (i<5) 
                printf(":"); 
        } 
        printf( "
"); 
    } 
    else { 
        fprintf( stderr, "can't get MAC address
"); 
        exit( 1); 
    } 
    return 0; 
}

原文地址:https://www.cnblogs.com/bugutian/p/5013927.html