linux系统状态(磁盘大小、内存、进程、cpu使用率、网络连接)

简介:

分享一下自己做的一个获取Linux系统状态的类(c++)

使用方式:声明一个该类的变量(即实例化),用实例调用相关接口即可。

头文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#ifndef LINUXSERVERSTATE_H
#define LINUXSERVERSTATE_H
#include <sys/types.h>
#include <unistd.h>
#include <string>
#include <vector>
#include <pthread.h>
namespace  LINUXSERV_STATE
{
#pragma pack(push)
#pragma pack(8)
struct  SysMemInfo
{
   unsigned  long  total; //单位:M
   unsigned  long  free ; //单位:M
};
struct  SysDiskInfo
{
   std::string   name; //sda1,sad2等等
   unsigned  long  total; //单位:M,不包括交换分区、CDROM等
   unsigned  long  free ; //单位:M
};
struct  SysNetInfo
{
   float  send; //kb
   float  recv; //kb
   float  total; //kb
};
struct  SysProcInfo
{
   std::string   name; //进程名字
   int            pid; //进程id
   int            cpu; //cpu使用率
   long       mem; //内存使用,单位Kb,linux内存指的是vmrss,即程序正在使用的物理内存,-1表示未获取到或获取错误
};
struct  SysProcTimeInfo
{
   unsigned  long  user; //进程在用户态执行的时间
   unsigned  long  kernel; //进程在内核态执行的时间
};
//linux src目录中的include/net/tcp_states.h,source目录一般位于/usr/src/linux*目录中
enum  SysNetState{
   TCP_ESTABLISHED = 1,
   TCP_SYN_SENT,
   TCP_SYN_RECV,
   TCP_FIN_WAIT1,
   TCP_FIN_WAIT2,
   TCP_TIME_WAIT,
   TCP_CLOSE,
   TCP_CLOSE_WAIT,
   TCP_LAST_ACK,
   TCP_LISTEN,
   TCP_CLOSING,     /* Now a valid state */
   TCP_MAX_STATES   /* Leave at the end! */
};
enum  SockType{UNKNOWN=0,TCP , UDP, TCP6, UDP6};
struct  SysNetConnInfo
{
   int                id;
   SockType  protocol;
   std::string   localAddr;
   int                localPort;
   std::string   remoteAddr;
   int                remotePort;
   SysNetState   state;
};
#pragma pack(pop)
void * CPUNetProcessCount( void * arg);
class  LinuxServerState
{
public :
     LinuxServerState();
     virtual      ~LinuxServerState();
                    
     int      GetMemInfo(SysMemInfo& memInfo);
     int      GetDiskInfo(std::vector<SysDiskInfo>& diskInfo,unsigned  long  &total,unsigned  long  &available);
     //返回cpu的利用率,返回-1表示超时或者其他错误
     int      GetCpuUsage();
     //sys net info
     SysNetInfo  GetNetInfo();
     //process info
     void     GetProcInfo(std::vector<SysProcInfo>& procInfo);
     //net connection info
     void     GetNetConnectionInfo(std::vector<SysNetConnInfo>& netConnInfo);
private :
     void     initialize();
     friend   void * CPUNetProcessCount( void * arg);
     int      m_cpuUsage;  //多个CPU的总的使用率
     pthread_mutex_t m_mutex;
     SysNetInfo  m_netInfo;
     pthread_t   m_countThread;
     std::vector<SysProcInfo>  m_procInfo;
     void *   m_threadRet;
     LinuxServerState( const  LinuxServerState& other);
     virtual      LinuxServerState& operator=( const  LinuxServerState& other);
     virtual      bool  operator==( const  LinuxServerState& other)  const ;
};
}
#endif // LINUXSERVERSTATE_H

源文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
#include "linuxserverstate.h"
#include <sys/sysinfo.h>//getmemInfo
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <climits>
#include <cstring>
#include <time.h>
#include <dirent.h>
#include <map>
#include <errno.h>
#include <iostream>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
using  namespace  std;
namespace  LINUXSERV_STATE
{
void * CPUNetProcessCount( void * arg)
{
     LinuxServerState* pMain = (LinuxServerState*)arg;
     //get all cpu usage
     unsigned  long  cpuTime, idleTime;
     unsigned  long     userT = 0, niceT = 0, systemT = 0, idleT = 0, ioT = 0, irqT = 0, softirqT = 0;
     char          cpubuf[8] = { '\0' };
     fstream          fProcStat( "/proc/stat" ,ios_base::in);
     fProcStat>>cpubuf>>userT>>niceT>>systemT>>idleT>>ioT>>irqT>>softirqT;
     cpuTime = userT + niceT + systemT + idleT + ioT + irqT + softirqT;
     idleTime = idleT;
     //get net stat
     fstream          fProcNetStat( "/proc/net/netstat" ,ios_base::in);
     char          bufNetStat[2048] = { '\0' }, ipExt[16] = { '\0' };
     unsigned  long     inNoRoutes = 0, inTruncPkts = 0, inMcastPkts = 0, outMcastPkts = 0, inBcastPkts = 0, outBcastPkts = 0;
     unsigned  long     inOctets = 0, outOctets = 0, inMcastOctets = 0, outMcastOctets = 0, inBcastOctets = 0, outBcastOctets = 0;
     time_t        sysTime;
     while (!fProcNetStat.eof())
     {
       fProcNetStat.getline(bufNetStat,2048);
       if (strncasecmp(bufNetStat, "tcpext" ,6) == 0)
     continue ;
       if (strncasecmp(bufNetStat, "ipext" ,5) == 0)
       {
     fProcNetStat.getline(bufNetStat,2048);
     sscanf (bufNetStat, "%s %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld" ,ipExt,
            &inNoRoutes,&inTruncPkts,&inMcastPkts,&outMcastPkts,&inBcastPkts,&outBcastPkts,
         &inOctets,&outOctets,&inMcastOctets,&outMcastOctets,&inBcastOctets,&outBcastOctets);
     sysTime =  time (NULL);
     break ;
       }
     }
     //initialize proc info
     char  dirName[128] = { '\0' },tmpbuf[2048] = { '\0' };
     long  utime, stime;
                        
     struct  dirent* ent = NULL;
     char  pidBuf[128] = { '\0' }, *endptr;
     DIR* pDirProc = opendir( "/proc" );
     map<pid_t,SysProcTimeInfo>    procTimeInfo;
     if (pDirProc == NULL)
       return  NULL;
     while ((ent = readdir(pDirProc))!= NULL)
     {
       long  pidNum =  strtol (ent->d_name,&endptr,10);
       if (pidNum == LONG_MAX || pidNum == LONG_MIN || endptr == ent->d_name)
       {
     continue ;
       }
       else
       {
     //初始化时间
     fstream fPidStat,fPidMem;
     int  i = 0;
     SysProcTimeInfo tmpProcTimeInfo;
     SysProcInfo tmpProcInfo;
     snprintf(dirName,128, "%s%d%s" , "/proc/" ,pidNum, "/stat" );
     try
     {
       fPidStat.open(dirName,ios_base::in);
     }
     catch (std::exception& e)
     {
       return  NULL;
     }
     fPidStat>>tmpbuf; //获取pid
     i++;
     fPidStat>>tmpbuf; //获取进程名字,名字由“()”包括
     i++;
     if ( strlen (tmpbuf) > 2)
       tmpProcInfo.name  = string(tmpbuf).substr(1, strlen (tmpbuf) -2);
     else
       continue ;
     for (; i < 14;i++)
       fPidStat>>tmpbuf;
                        
     //14项表示utime,15项表示stime
     fPidStat >> utime;
     i++;
     fPidStat >> stime;
     i++;
     tmpProcTimeInfo.user    = utime;
     tmpProcTimeInfo.kernel  = stime;
     utime           = 0;
     stime           = 0;
                        
     procTimeInfo.insert(pair<pid_t,SysProcTimeInfo>(pidNum,tmpProcTimeInfo));
     tmpProcInfo.cpu = 0;
     tmpProcInfo.pid = pidNum;
                        
     //初始化内存,
     char  *pstrtolong;
     memset (dirName, '\0' ,128);
     snprintf(dirName,128, "%s%d%s" , "/proc/" ,pidNum, "/status" );
     fPidMem.open(dirName,ios_base::in);
     while (!fPidMem.eof())
     {
       fPidMem >> tmpbuf;
       if (strncasecmp(tmpbuf, "vmrss" ,5) == 0)
       {
         fPidMem >> tmpbuf;
         unsigned  long  vmrss =  strtol (tmpbuf,&pstrtolong,10);
         if (vmrss == LONG_MAX || vmrss == LONG_MIN || pstrtolong == tmpbuf)
         {
           tmpProcInfo.mem = -1;
         }
         else
           tmpProcInfo.mem = vmrss;
         if (0 == pthread_mutex_trylock(&pMain->m_mutex))
         {
           pMain->m_procInfo.push_back(tmpProcInfo);
           pthread_mutex_unlock(&pMain->m_mutex);
         }
         break ;
       }
     }
                        
     memset (dirName, '\0' ,128);
     memset (tmpbuf, '\0' ,2048);
       }
     }
     closedir(pDirProc);
     pDirProc    = NULL;
     while (1)
     {
       sleep(1);
       //cpu usage
       unsigned  long  cpuTimeNow = 0, idleTimeNow = 0;
       int  cpu = 0;
       fProcStat.seekg(0,ios_base::beg);
       fProcStat>>cpubuf>>userT>>niceT>>systemT>>idleT>>ioT>>irqT>>softirqT;
       cpuTimeNow = userT + niceT + systemT + idleT + ioT + irqT + softirqT;
       idleTimeNow = idleT;
                          
       cpu = 100 - (idleTimeNow - idleTime)*100/(cpuTimeNow - cpuTime);
       idleTime  = idleTimeNow;
       cpuTime   = cpuTimeNow;
       if (0 == pthread_mutex_trylock(&pMain->m_mutex))
       {
     pMain->m_cpuUsage = cpu;
     pthread_mutex_unlock(&pMain->m_mutex);
       }
       //else暂时不处理
       //net stat
       unsigned  long  inOctetsTmp = 0,outOctetsTmp = 0;
       fProcNetStat.seekg(0,ios_base::beg);
       time_t     timeNow =  time (NULL);
       while (!fProcNetStat.eof())
       {
     fProcNetStat.getline(bufNetStat,2048);
     if (strncasecmp(bufNetStat, "tcpext" ,6) == 0)
       continue ;
     if (strncasecmp(bufNetStat, "ipext" ,5) == 0)
     {
       fProcNetStat.getline(bufNetStat,2048);
       sscanf (bufNetStat, "%s %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld %ld" ,ipExt,
         &inNoRoutes,&inTruncPkts,&inMcastPkts,&outMcastPkts,&inBcastPkts,&outBcastPkts,
         &inOctetsTmp,&outOctetsTmp,&inMcastOctets,&outMcastOctets,&inBcastOctets,&outBcastOctets);
       timeNow =  time (NULL);
       break ;
     }
       }
       SysNetInfo tmpNetInfo;
       tmpNetInfo.recv = (inOctetsTmp - inOctets)/1024/(timeNow - sysTime);
       tmpNetInfo.send = (outOctetsTmp - outOctets)/1024/(timeNow - sysTime);
       tmpNetInfo.total = tmpNetInfo.recv + tmpNetInfo.send;
                          
       sysTime   = timeNow;
       inOctets  = inOctetsTmp;
       outOctets = outOctetsTmp;
       if (0 == pthread_mutex_trylock(&pMain->m_mutex))
       {
     pMain->m_netInfo = tmpNetInfo;
     pthread_mutex_unlock(&pMain->m_mutex);
       }
       //proc info
       if (0 == pthread_mutex_trylock(&pMain->m_mutex))
       {
     pMain->m_procInfo.clear();
     pthread_mutex_unlock(&pMain->m_mutex);
       }
       pDirProc = opendir( "/proc" );
       while ((ent = readdir(pDirProc))!= NULL)
       {
     long  pidNum =  strtol (ent->d_name,&endptr,10);
     if (pidNum == LONG_MAX || pidNum == LONG_MIN || endptr == ent->d_name)
     {
       continue ;
     }
     else
     {
       //初始化时间
       fstream fPidStat,fPidMem;
       int  i = 0;
       snprintf(dirName,128, "%s%d%s" , "/proc/" ,pidNum, "/stat" );
       fPidStat.open(dirName,ios_base::in);
       fPidStat>>tmpbuf; //获取pid
       i++;
       fPidStat>>tmpbuf; //获取进程名字,名字由“()”包括
       i++;
       SysProcInfo   tmpProcInfo;
       if ( strlen (tmpbuf) > 2)
         tmpProcInfo.name    = string(tmpbuf).substr(1, strlen (tmpbuf) -2);
       else
         cout<< "pid:\t" <<pidNum<< "tmpbuf:\t" <<tmpbuf<<endl;
       for (; i < 14;i++)
       {
         fPidStat>>tmpbuf;
       }
       //14项表示utime,15项表示stime
       fPidStat >> utime;
       fPidStat >> stime;
       map<pid_t,SysProcTimeInfo>::iterator it = procTimeInfo.find((pid_t)pidNum);
       if (it == procTimeInfo.end())
       {
         SysProcTimeInfo tmpProcTimeInfo;
         tmpProcTimeInfo.user    = utime;
         tmpProcTimeInfo.kernel  = stime;
         procTimeInfo.insert(pair<pid_t,SysProcTimeInfo>(pidNum,tmpProcTimeInfo));
         tmpProcInfo.cpu = 0;
       }
       else
       {
         tmpProcInfo.cpu = utime + stime - it->second.kernel - it->second.user;
         if (tmpProcInfo.cpu > 100)
           tmpProcInfo.cpu = 100;
         if (tmpProcInfo.cpu < 0)
           tmpProcInfo.cpu = 0;
         it->second.kernel    = stime;
         it->second.user  = utime;
       }
       utime         = 0;
       stime         = 0;
       tmpProcInfo.pid   = pidNum;
       //获取内存
       char  *pstrtolong;
       memset (dirName, '\0' ,128);
       snprintf(dirName,128, "%s%d%s" , "/proc/" ,pidNum, "/status" );
       fPidMem.open(dirName,ios_base::in);
       while (!fPidMem.eof())
       {
         fPidMem >> tmpbuf;
         if (strncasecmp(tmpbuf, "vmrss" ,5) == 0)
         {
           fPidMem >> tmpbuf;
           unsigned  long  vmrss =  strtol (tmpbuf,&pstrtolong,10);
           if (vmrss == LONG_MAX || vmrss == LONG_MIN || pstrtolong == tmpbuf)
           {
         tmpProcInfo.mem = -1;
           }
           else
         tmpProcInfo.mem = vmrss;
           if (0 == pthread_mutex_trylock(&pMain->m_mutex))
           {
         pMain->m_procInfo.push_back(tmpProcInfo);
         pthread_mutex_unlock(&pMain->m_mutex);
           }
           break ;
         }
       }
       memset (dirName, '\0' ,128);
       memset (tmpbuf, '\0' ,2048);
     }
       }
       closedir(pDirProc);
     } //main
                        
     return  NULL;
}
LinuxServerState::LinuxServerState()
{
   m_cpuUsage        = 0;
   m_countThread     = 0;
   m_threadRet       = NULL;
   m_netInfo.total   = 0;
   m_netInfo.recv    = 0;
   m_netInfo.send    = 0;
   initialize();
}
LinuxServerState::LinuxServerState( const  LinuxServerState& other)
{
}
LinuxServerState::~LinuxServerState()
{
   if (m_countThread != 0)
     pthread_join(m_countThread,NULL);
   pthread_mutex_destroy(&m_mutex);
}
LinuxServerState& LinuxServerState::operator=( const  LinuxServerState& other)
{
     return  * this ;
}
bool  LinuxServerState::operator==( const  LinuxServerState& other)  const
{
///TODO: return ...;
}
void  LinuxServerState::initialize()
{
   //pthread_mutexatt matt;
   //pthread_mutexattr_init(&matt);
                      
   pthread_mutex_init(&m_mutex,NULL);
   pthread_create(&m_countThread,NULL,&CPUNetProcessCount, this );
}
int  LinuxServerState::GetCpuUsage()
{
   timespec  tmp;
   tmp.tv_nsec   = 0;
   tmp.tv_sec    = 1;
   int  cpu   = 0;
   if (0 == pthread_mutex_timedlock(&m_mutex,&tmp))
   {
     cpu     = m_cpuUsage;
     pthread_mutex_unlock(&m_mutex);
   }
   else
     return  -1;
   if (cpu > 100)
     return  100;
   if (cpu < 0)
     return  0;
   return  cpu;
}
int  LinuxServerState::GetMemInfo(SysMemInfo& memInfo)
{
   struct  sysinfo    tmp;
   int            ret = 0;
   ret  =        sysinfo(&tmp);
   if (ret == 0)
   {
     memInfo. free     = (unsigned  long )tmp.freeram/(1024*1024);
     memInfo.total   = (unsigned  long )tmp.totalram/(1024*1024);
   }
   return  ret;
}
int  LinuxServerState::GetDiskInfo(std::vector<SysDiskInfo>& diskInfo,unsigned  long  &total,unsigned  long  &available)
{
   total     = 0;
   available = 0;
   char       buf[128] = { '\0' };
   string    fileName;
   char       *p;
   fstream   fProc( "/proc/partitions" ,ios_base::in);
   unsigned  long  total2 = 0, free2 = 0, sumTotal = 0, sumFree = 0;
   int        major = 0, minor = 0;
   //首先计算总大小及各个分区的大小,包括交换分区,然后用df命令获取可用空间
   while (!fProc.eof())
   {
     fProc>>fileName;
     total2  =  strtol (fileName.c_str(),&p,10);
     if (total2 == 0)
       continue ;
     else  if (total2 == LONG_MAX || total2 == LONG_MIN || p == fileName.c_str())
       return  total2;
     else
     {
       major     = total2;
       fProc>>minor;
       fProc>>total2;
                          
       fProc>>fileName;
                          
       SysDiskInfo tmp;
       tmp.total = (unsigned  long )(total2/1024);
       tmp. free   = 0;
       tmp.name  = fileName;
                         
       diskInfo.push_back(tmp);
       if ((fileName.find( "sd" )!= string::npos || fileName.find( "hd" ) != string::npos) &&
     !(fileName[fileName.size()-1] >= '0'  &&  fileName[fileName.size()-1] <= '9' ))
     sumTotal += tmp.total;
       fileName.clear();
     }
   }
   //获取可用空间
   const  char         *command =  "df" ;
   const  char         *type    =  "r" ;
   FILE   *pFile      = popen(command,type);
   char   buf2[1024]  = { '\0' };
   char   filesys[32] = { '\0' }, usage[8] = { '\0' }, mountedon[32] = { '\0' };
   unsigned  long  kblocks = 0, used = 0, available2 = 0;
   if (pFile == NULL)
     return  -1;
   vector<SysDiskInfo>::iterator it;
   while  (! feof  (pFile) )
   {
       if  ( fgets  (buf2 , 1024 , pFile) == NULL )
     break ;
       sscanf (buf2, "%s %ld %ld %ld %s %s" ,filesys,&kblocks,&used,&available2,usage,mountedon);
       string ff(filesys);
       if (ff.rfind( "/" ) == string::npos)
     continue ;
       for (it = diskInfo.begin(); it != diskInfo.end();it++)
       {
     if (it->name == ff.substr(ff.rfind( "/" )+1))
     {
       it-> free    = (unsigned  long )(available2/1024);
       sumFree   += it-> free ;
     }
       }
       memset (buf2, '\0' ,1024);
       memset (filesys, '\0' ,32);
       memset (mountedon, '\0' ,32);
       memset (usage, '\0' ,8);
       kblocks   = 0;
       used  = 0;
       available2 = 0;
   }
   pclose(pFile);
   total     = sumTotal;
   available     = sumFree;
   return  0;
}
SysNetInfo LinuxServerState::GetNetInfo()
{
   SysNetInfo    tmpNetInfo;
   tmpNetInfo.recv   = 0;
   tmpNetInfo.send   = 0;
   tmpNetInfo.total  = 0;
   timespec  tmp;
   tmp.tv_nsec   = 0;
   tmp.tv_sec    = 1;
   if (0 == pthread_mutex_timedlock(&m_mutex,&tmp))
   {
     tmpNetInfo      = m_netInfo;
     pthread_mutex_unlock(&m_mutex);
   }
   return  tmpNetInfo;
}
void  LinuxServerState::GetProcInfo(std::vector<SysProcInfo>& procInfo)
{
   timespec  tmp;
   tmp.tv_nsec   = 0;
   tmp.tv_sec    = 1;
                      
   if (0 == pthread_mutex_timedlock(&m_mutex,&tmp))
   {
     procInfo        = m_procInfo;
     pthread_mutex_unlock(&m_mutex);
   }
}
void  LinuxServerState::GetNetConnectionInfo(std::vector<SysNetConnInfo>& netConnInfo)
{
   int  i = 0,id = 0;
   char  buf[1024] = { '\0' };
   while (i++ < 4)
   {
     fstream     fInfo;
     SockType        stateType = UNKNOWN;
                        
     if (i == 1)
     {
       fInfo.open( "/proc/net/tcp" ,ios_base::in);
       stateType  = TCP;
     }
     else  if (i == 2)
     {
       fInfo.open( "/proc/net/udp" ,ios_base::in);
       stateType = UDP;
     }
     else  if (i == 3)
     {
       fInfo.open( "/proc/net/tcp6" ,ios_base::in);
       stateType = TCP6;
     }
     else  if (i == 4)
     {
       fInfo.open( "/proc/net/udp6" ,ios_base::in);
       stateType = UDP6;
     }
     if (stateType == UNKNOWN)
       continue ;
                        
     while (!fInfo.eof())
     {
       SysNetConnInfo    tmpConnInfo;
                          
       char  sl[6] = { '\0' },localaddr[32] = { '\0' },remoteaddr[32] = { '\0' };
       fInfo.getline(buf,1024);
       unsigned  long  llocal = 0, lremote = 0;
       int        localPort = 0, remotePort = 0, st = 0;
       int  ret;
       if (i == 1 || i == 2)
       {
     ret =  sscanf (buf, "%s%x:%x%x:%x%x" ,sl,&llocal,&localPort,&lremote,&remotePort,&st);
     if (ret != 6)
       continue ;
     in_addr         tmpAddr;
     tmpAddr.s_addr      = llocal;
     tmpConnInfo.localAddr   = inet_ntoa(tmpAddr);
     tmpAddr.s_addr      = lremote;
     tmpConnInfo.remoteAddr  = inet_ntoa(tmpAddr);
       }
                          
       else  if (i == 3 || i == 4 )
       {
     ret =  sscanf (buf, "%s%32s:%x%32s:%x%x" ,sl,&localaddr,&localPort,&remoteaddr,&remotePort,&st);
     if (ret != 6)
       continue ;
     char     tmp[64] = { '\0' };
     int  pos = 0;
     for ( int  j = 0;j < 32; j++)
     {
       tmp[pos++] = localaddr[j];
       if ((j % 4) == 3 && j != 31)
         tmp[pos++] =  ':' ;
     }
     tmpConnInfo.localAddr   = string(tmp);
     memset (tmp, '\0' ,64);
     pos  = 0;
     for ( int  j = 0;j < 32; j++)
     {
       tmp[pos++] = remoteaddr[j];
       if ((j % 4) == 3 && j != 31)
         tmp[pos++] =  ':' ;
     }
     tmpConnInfo.remoteAddr  = string(tmp);
       }
                         
       tmpConnInfo.localPort = localPort;
       tmpConnInfo.remotePort    = remotePort;
       tmpConnInfo.id        = id++;
       tmpConnInfo.protocol  = stateType;
       tmpConnInfo.state     = (SysNetState)st;
       netConnInfo.push_back(tmpConnInfo);
     }
     fInfo.close();
   }
                      
}
}









本文转自 hakuyo 51CTO博客,原文链接:http://blog.51cto.com/hakuyo/1218145,如需转载请自行联系原作者

目录
相关文章
|
5月前
|
Ubuntu 网络协议 网络安全
解决Ubuntu系统的网络连接问题
以上步骤通常可以帮助解决大多数Ubuntu系统的网络连接问题。如果问题仍然存在,可能需要更深入的诊断,或考虑联系网络管理员或专业技术人员。
1230 18
|
5月前
|
监控 安全 网络协议
Cisco Identity Services Engine (ISE) 3.5 发布 - 基于身份的网络访问控制和策略实施系统
Cisco Identity Services Engine (ISE) 3.5 发布 - 基于身份的网络访问控制和策略实施系统
592 1
Cisco Identity Services Engine (ISE) 3.5 发布 - 基于身份的网络访问控制和策略实施系统
|
5月前
|
机器学习/深度学习 大数据 关系型数据库
基于python大数据的青少年网络使用情况分析及预测系统
本研究基于Python大数据技术,构建青少年网络行为分析系统,旨在破解现有防沉迷模式下用户画像模糊、预警滞后等难题。通过整合多平台亿级数据,运用机器学习实现精准行为预测与实时干预,推动数字治理向“数据驱动”转型,为家庭、学校及政府提供科学决策支持,助力青少年健康上网。
|
6月前
|
机器学习/深度学习 传感器 算法
【无人车路径跟踪】基于神经网络的数据驱动迭代学习控制(ILC)算法,用于具有未知模型和重复任务的非线性单输入单输出(SISO)离散时间系统的无人车的路径跟踪(Matlab代码实现)
【无人车路径跟踪】基于神经网络的数据驱动迭代学习控制(ILC)算法,用于具有未知模型和重复任务的非线性单输入单输出(SISO)离散时间系统的无人车的路径跟踪(Matlab代码实现)
414 2
|
7月前
|
安全 KVM 虚拟化
Cisco Identity Services Engine (ISE) 3.4 - 基于身份的网络访问控制和策略实施系统
Cisco Identity Services Engine (ISE) 3.4 - 基于身份的网络访问控制和策略实施系统
401 2
Cisco Identity Services Engine (ISE) 3.4 - 基于身份的网络访问控制和策略实施系统
|
7月前
|
运维 Linux 开发者
Linux系统中使用Python的ping3库进行网络连通性测试
以上步骤展示了如何利用 Python 的 `ping3` 库来检测网络连通性,并且提供了基本错误处理方法以确保程序能够优雅地处理各种意外情形。通过简洁明快、易读易懂、实操性强等特点使得该方法非常适合开发者或系统管理员快速集成至自动化工具链之内进行日常运维任务之需求满足。
477 18
|
5月前
|
机器学习/深度学习 分布式计算 Java
Java与图神经网络:构建企业级知识图谱与智能推理系统
图神经网络(GNN)作为处理非欧几里得数据的前沿技术,正成为企业知识管理和智能推理的核心引擎。本文深入探讨如何在Java生态中构建基于GNN的知识图谱系统,涵盖从图数据建模、GNN模型集成、分布式图计算到实时推理的全流程。通过具体的代码实现和架构设计,展示如何将先进的图神经网络技术融入传统Java企业应用,为构建下一代智能决策系统提供完整解决方案。
527 0
|
7月前
|
机器学习/深度学习 数据采集 算法
【电力系统】MATLAB环境下基于神经网络的电力系统稳定性预测研究(Matlab代码实现)
【电力系统】MATLAB环境下基于神经网络的电力系统稳定性预测研究(Matlab代码实现)
154 1
|
7月前
|
算法 安全 网络安全
【多智能体系统】遭受DoS攻击的网络物理多智能体系统的弹性模型预测控制MPC研究(Simulink仿真实现)
【多智能体系统】遭受DoS攻击的网络物理多智能体系统的弹性模型预测控制MPC研究(Simulink仿真实现)
293 0