一个轻量级的网络流量监控程序,只能在局域网中使用。
主要用到GetIfTable(),和GetIfEntry() 两个API。界面用QT做,可以隐藏在系统托盘中。
截图
核心代码如下
- void NetFlow::getFlow() {
- // 记录上一次函数调用时的总流量和时间,在后面计算流量速度的时候用到
- preInFlow = inFlow;
- preOutFlow = outFlow;
- preTime = currTime;
- inFlow = 0.0f;
- outFlow = 0.0f;
- currTime = GetTickCount();
- int i;
- pIfTable = (MIB_IFTABLE *) MALLOC(sizeof (MIB_IFTABLE));
- if (pIfTable == NULL) {
- printf("Error allocating memory needed to call GetIfTable/n");
- return;
- }
- dwSize = sizeof (MIB_IFTABLE);
- if (GetIfTable(pIfTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) {
- FREE(pIfTable);
- pIfTable = (MIB_IFTABLE *) MALLOC(dwSize);
- if (pIfTable == NULL) {
- printf("Error allocating memory/n");
- return;
- }
- }
- if ((dwRetVal = GetIfTable(pIfTable, &dwSize, 0)) == NO_ERROR) {
- if (pIfTable->dwNumEntries > 0) {
- pIfRow = (MIB_IFROW *) MALLOC(sizeof (MIB_IFROW));
- if (pIfRow == NULL) {
- printf("Error allocating memory/n");
- if (pIfTable != NULL) {
- FREE(pIfTable);
- pIfTable = NULL;
- }
- return;
- }
- printf("/tNum Entries: %ld/n/n", pIfTable->dwNumEntries);
- // 枚举所有接口
- for (i = 0; i < (int) pIfTable->dwNumEntries; i++) {
- pIfRow->dwIndex = pIfTable->table[i].dwIndex;
- if ((dwRetVal = GetIfEntry(pIfRow)) == NO_ERROR) {
- // 排除环回接口的流量
- if(pIfRow->dwType != MIB_IF_TYPE_LOOPBACK) {
- inFlow += pIfRow->dwInOctets;
- outFlow += pIfRow->dwOutOctets;
- }
- }
- else {
- printf("GetIfEntry failed for index %d with error: %ld/n",
- i, dwRetVal);
- }
- }
- } else {
- printf("/tGetIfTable failed with error: %ld/n", dwRetVal);
- }
- }
- FREE(pIfTable);
- FREE(pIfRow);
- // 计算流量,速度=总流量 / 所经过的时间
- float inSpeed = (inFlow - preInFlow) / ((float)(currTime - preTime) / 1000.0f);
- float outSpeed = (outFlow - preOutFlow) / ((float)(currTime - preTime) / 1000.0f);
- char buffer[100];
- sprintf(buffer, "Download: %.2fk/s Upload: %.2fk/s", inSpeed / 1000.0f, outSpeed / 1000.0f);
- bodyEdit->setText(buffer);
- trayIcon->setToolTip(QString(buffer));
- }