1 /*
2 * Copyright (C) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #include "include/Network.h"
16 #include <sstream>
17 #include <fstream>
18 #include <iostream>
19 #include <string>
20 #include <unistd.h>
21 #include <dirent.h>
22 #include <cstdio>
23 #include <cstdlib>
24 #include <climits>
25 #include <cctype>
26 #include "sys/time.h"
27 #include "securec.h"
28 #include "include/sp_utils.h"
29 #include "include/sp_log.h"
30 #define LARGE_BUFF_MAX_LEN (256)
31 namespace OHOS {
32 namespace SmartPerf {
ItemData()33 std::map<std::string, std::string> Network::ItemData()
34 {
35 std::map<std::string, std::string> result;
36 std::map<std::string, std::string> networkInfo = Network::GetNetworkInfo();
37 result = networkInfo;
38 return result;
39 }
40
GetNetworkInfo()41 std::map<std::string, std::string> Network::GetNetworkInfo()
42 {
43 std::map<std::string, std::string> networkInfo;
44 char buff[LARGE_BUFF_MAX_LEN];
45 FILE *fp = fopen("/proc/net/dev", "r");
46 if (fp == nullptr) {
47 std::cout << "net work node is not accessed" << std::endl;
48 return networkInfo;
49 }
50 while (fgets(buff, LARGE_BUFF_MAX_LEN, fp)) {
51 if (strstr(buff, "rmnet") || strstr(buff, "eth") || strstr(buff, "wlan")) {
52 if (sscanf_s(buff, "%*s%lld%*lld%*lld%*lld%*lld%*lld%*lld%*lld%lld%*lld%*lld%*lld%*lld%*lld%*lld%*lld",
53 &curRx, &curTx) < 0) {
54 return networkInfo;
55 }
56 allTx += curTx;
57 allRx += curRx;
58 }
59 }
60 fclose(fp);
61 if (isFirst) {
62 networkInfo["networkUp"] = std::to_string(prevTx);
63 networkInfo["networkDown"] = std::to_string(prevRx);
64 isFirst = false;
65 prevTx = allTx;
66 prevRx = allRx;
67 allTx = 0;
68 allRx = 0;
69 return networkInfo;
70 }
71 if ((allTx == 0 && allRx == 0) || (allTx <= prevTx && allRx <= prevRx)) {
72 networkInfo["networkUp"] = "0";
73 networkInfo["networkDown"] = "0";
74 prevTx = allTx;
75 prevRx = allRx;
76 allTx = 0;
77 allRx = 0;
78 return networkInfo;
79 }
80 diffTx = allTx - prevTx;
81 prevTx = allTx;
82 diffRx = allRx - prevRx;
83 prevRx = allRx;
84 allTx = 0;
85 allRx = 0;
86 networkInfo["networkUp"] = std::to_string(diffTx);
87 networkInfo["networkDown"] = std::to_string(diffRx);
88 return networkInfo;
89 }
90 }
91 }
92