⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 getnetinfo.c

📁 读取TCP连接数
💻 C
字号:
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <unistd.h>#ifdef __ia64__#define USE_EFI#endif /* __ia64__ */#include "getnetinfo.h"#define GET_NETSTAT_S_CMD  "netstat -s"#define TCP_BEGIN_LABEL  "Tcp:"#define TCP_ACTIVE_CONN_OPENS  "passive connection openings"#define UDP_BEGIN_LABEL  "Udp:"#define UDP_PKG_RECEIVED  "packets received"#define UDP_PKG_SENT  "packets sent"//全局网络连接信息结构体TCP_UDP_Info g_tcp_udp_info;int getnetstatInfo(void){    FILE *pFile  = NULL;    char buf[256];    char number[32];    char *pFind;    pFile = popen(GET_NETSTAT_S_CMD , "r");    if (!pFile)    {        return -1;    }    g_tcp_udp_info._tcp_passive_conn = 0;    g_tcp_udp_info._udp_pkg_rec = 0;    g_tcp_udp_info._udp_pkg_snd = 0;    while(!feof(pFile))    {               bzero(buf,sizeof(buf));        if (!(fgets(buf, sizeof(buf), pFile)))            break;                         //分析TCP连接数.        pFind=strstr(buf,TCP_BEGIN_LABEL);        if(pFind!=NULL)        {            //向下走两行就是:TCP_ACTIVE_CONN_OPENS            if (!(fgets(buf, sizeof(buf), pFile)))               break;             if (!(fgets(buf, sizeof(buf), pFile)))               break;             pFind=strstr(buf,TCP_ACTIVE_CONN_OPENS);            if(pFind!=NULL)            {                //这一行就是TCP的被动连接数.                             sscanf(buf, "%*[ ]%d",&g_tcp_udp_info._tcp_passive_conn);  //只读取数字字符                  }        }        //分析UPD连接.        pFind=strstr(buf,UDP_BEGIN_LABEL);        if(pFind!=NULL)        {            //向下走一行就是:UDP_PKG_RECEIVED            if (!(fgets(buf, sizeof(buf), pFile)))               break;             pFind=strstr(buf,UDP_PKG_RECEIVED);            if(pFind!=NULL)            {                //这一行就是upd的包接收数                sscanf(buf, "%*[ ]%d",&g_tcp_udp_info._udp_pkg_rec);              }            for(unsigned int i=0;i<3;++i)            {                if (!(fgets(buf, sizeof(buf), pFile)))                    break;             }            pFind=strstr(buf,UDP_PKG_SENT);            if(pFind!=NULL)            {                //这一行就是upd的包发送数                sscanf(buf, "%*[ ]%d",&g_tcp_udp_info._udp_pkg_snd);              }        }    }    pclose(pFile);    printf("TCP:active connections openings=%ld\n",g_tcp_udp_info._tcp_passive_conn);    printf("UDP:packets received=%ld\n",g_tcp_udp_info._udp_pkg_rec);    printf("UDP:packets sent=%ld\n",g_tcp_udp_info._udp_pkg_snd);        return 0;}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -