用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 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* |bc -l` SYS_Rate=`expr -$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 $ ]; then
LISTEN_PATH=$
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[] = {}; while(fgets(buf, sizeof(buf), file) != NULL)
{
char tmpbuf[]={};
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[] = {}; while(fgets(buf, sizeof(buf), file) != NULL)
{
char tmpbuf[]={};
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[] = {}; while(fgets(buf, sizeof(buf), file) != NULL)
{
char tmpbuf[]={};
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[] = {}; while(fgets(buf, sizeof(buf), file) != NULL)
{
char tmpbuf[]={};
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 ;
}

三、获取当前活动的网卡和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 = ;
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") != ) {
// printf("%s IP Address:%s\n", ifAddrStruct->ifa_name, ip);
if (n == ){
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[][INET_ADDRSTRLEN];
memset(ip, , sizeof(ip));
int n;
for (n=get_local_ip(*ip); n>; n--) {
printf("%s\n", ip[n-]);
}
return ;
}

(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[];
char *ifnames = ifname_buf;
int count = ; void add_interface_name(const char * name)
{
int i;
for (i=;i<count;i++)
{
if (!strcmp(ifnames+i*IFNAMSIZ, name))
return;
}
strncpy(ifnames+(count++)*IFNAMSIZ, name, IFNAMSIZ-);
} 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 == '\0')
return NULL;
p++;
break;
}
*name++ = *p++;
}
*name++ = '\0';
return p;
} // get /proc/net/dev interface name list into buffer
// return 0 if success
int get_procnet_list()
{
FILE *fh;
char buf[];
fh = fopen("/proc/net/dev", "r");
if (!fh)
return -; 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 ;
} long mac_addr_sys ( u_char *addr)
{
/* implementation for Linux */
struct ifreq ifr;
struct ifreq *IFR;
struct ifconf ifc;
char buf[];
int s, i;
int ok = ; // clear buffer
memset(ifname_buf, , sizeof(ifname_buf)); s = socket(AF_INET, SOCK_DGRAM, );
if (s==-) {
return -;
} 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 >= ; IFR++) {
add_interface_name(IFR->ifr_name);
}
// put the /proc/net/dev interface names in the list
if (get_procnet_list())
return -; // get the first mac address of eth* device hardware address
for (i = ; i < count; i++) {
strcpy(ifr.ifr_name, ifnames + i*IFNAMSIZ);
if (!strncmp(ifr.ifr_name, "eth", ))
if (ioctl(s, SIOCGIFFLAGS, &ifr) == ) {
if (! (ifr.ifr_flags & IFF_LOOPBACK)) {
if (ioctl(s, SIOCGIFHWADDR, &ifr) == ) {
char *p = (char *)ifr.ifr_hwaddr.sa_data;
if (!*((int *)p) && !*((int *)(p+)) )
continue;
// if not 00:00:00:00:00:00, yes, we get the real mac addr
ok = ;
break;
}
}
}
} close(s);
if (ok) {
bcopy( ifr.ifr_hwaddr.sa_data, addr, );
}
else {
return -;
}
return ;
} int main( int argc, char **argv)
{
long stat;
int i;
u_char addr[]; stat = mac_addr_sys( addr);
if ( == stat) {
printf( "MAC address = ");
for (i=; i<; ++i) {
printf("%2.2x", addr[i]);
if (i<)
printf(":");
}
printf( "\n");
}
else {
fprintf( stderr, "can't get MAC address\n");
exit( );
}
return ;
}

用C++和shell获取本机CPU、网卡IO、内存、磁盘等的基本信息的更多相关文章

  1. 用 shell 获取本机的网卡名称

    用 shell 获取本机的网卡名称 # 用 shell 获取本机的网卡名称 ls /sys/class/net # 或者 ifconfig | grep "Link" | awk ...

  2. Golang利用第三方包获取本机cpu使用率以及内存使用情况

    第三方包下载 $ github.com/shirou/gopsutil 获取内存方面的信息 package main import ( "fmt" "github.com ...

  3. 获取本机CPU,硬盘等使用情况

    早上的时候接到主管的一个任务,要获取服务器上的cpu,硬盘, 数据库等 的使用情况,并以邮件的方式发给boss, = =没办法,公司的服务器真是不敢恭维,顺便吐槽一下公司的网速,卡的时候30k左右徘徊 ...

  4. 编程获取linux的CPU使用的内存使用情况

    Linux可用下top.ps命令检查当前的cpu.mem用法.下面简单的例子: 一.采用ps查看资源消耗的过程 ps -aux 当您查看进程信息,第三列是CPU入住. [root@localhost ...

  5. [No0000112]ComputerInfo,C#获取计算机信息(cpu使用率,内存占用率,硬盘,网络信息)

    github地址:https://github.com/charygao/SmsComputerMonitor 软件用于实时监控当前系统资源等情况,并调用接口,当资源被超额占用时,发送警报到个人手机: ...

  6. 基于WMI获取本机真实网卡物理地址和IP地址

    using System; using System.Collections.Generic; using System.Management; using System.Runtime.Intero ...

  7. C# 获取本机CPU序列号,MAC地址,硬盘ID,本机IP地址,计算机名,物理内存,PC类型

    首先引入服务 然后 调用 本文转载自http://blog.sina.com.cn/s/blog_7eeb43210101hf7f.html public class Computer { publi ...

  8. 获取Windows操作系统的CPU使用率以及内存使用率

    此功能参考了ProcessHacker项目的代码. 声明定义 typedef struct _UINT64_DELTA { ULONG64 Value; ULONG64 Delta; } UINT64 ...

  9. Linux C 获取本机所有网卡的 IP,Mask

    0 运行环境 本机系统:Windows 10 虚拟机软件:Oracle VM VirtualBox 6 虚拟机系统:Ubuntu 18 1 代码 #include <sys/ioctl.h> ...

随机推荐

  1. HTML页面禁止选择、页面禁止复制、页面禁止右键

    HTML页面内容禁止选择.复制.右键刚在一个看一个站点的源代码的的时候发现的,其实原来真的很简单 <body leftmargin=0 topmargin=0 oncontextmenu='re ...

  2. Sublime Text 收藏笔记

    Sublime Text:初学者不知道的那些事 转载自: http://blog.jobbole.com/23949/

  3. 【转载】CentOS 6.4下Squid代理服务器的安装与配置

    一.简介 代理服务器英文全称是Proxy Server,其功能就是代理网络用户去取得网络信息. Squid是一个缓存Internet 数据的软件,其接收用户的下载申请,并自动处理所下载的数据.当一个用 ...

  4. Java代码规范

    Java代码规范 本Java代码规范以SUN的标准Java代码规范为基础,为适应我们公司的实际需要,可能会做一些修改.本文档中没有说明的地方,请参看SUN Java标准代码规范.如果两边有冲突,以SU ...

  5. jquery最常用的几个方法。

    jquery使用手册:http://www.eduyo.com/doc/jquery/cheatsheet.html addClass 样式: <style> .textRed { col ...

  6. jqGrid 最常用的属性和事件,供平时参考(转)

    [html] <html> ... <table id="list1"></table> <div id="pager1&quo ...

  7. 安装使用ubuntu问题汇总

    很早以前就安装了ubuntu系统,可是一直没怎么用,也没有深入研究.这两天重装了一下windows,顺带着也重新装了一遍最新的ubuntu14.04.期间碰到了不少问题,一个个解决也花费了不少时间.所 ...

  8. 开发Eclipse自定义控件

    摘自:http://www.ibm.com/developerworks/cn/opensource/os-eclipcntl/ 我们在开发自定义控件时主要考虑以下问题: 1. 自定义控件的绘制:通常 ...

  9. 理解 Linux 网络栈(1):Linux 网络协议栈简单总结

    本系列文章总结 Linux 网络栈,包括: (1)Linux 网络协议栈总结 (2)非虚拟化Linux环境中的网络分段卸载技术 GSO/TSO/UFO/LRO/GRO (3)QEMU/KVM + Vx ...

  10. C++浅析——虚函数的动态和静态绑定

    源自一道面试题,觉得很有意思 class CBase { public: virtual void PrintData(int nData = 111); }; void CBase::PrintDa ...