94 }
95 }
96
97 - (void)netSpeedNotification{
98 [self checkNetworkflow];
99 }
100
101 -(NSString *)bytesToAvaiUnit:(int)bytes
102 {
103 if(bytes < 10)
104 {
105 return [NSString stringWithFormat:@"0KB"];
106 }
107 else if(bytes >= 10 && bytes < 1024 * 1024) // KB
108 {
109 return [NSString stringWithFormat:@"%.1fKB", (double)bytes / 1024];
110 }
111 else if(bytes >= 1024 * 1024 && bytes < 1024 * 1024 * 1024) // MB
112 {
113 return [NSString stringWithFormat:@"%.1fMB", (double)bytes / (1024 * 1024)];
114 }
115 else // GB
116 {
117 return [NSString stringWithFormat:@"%.1fGB", (double)bytes / (1024 * 1024 * 1024)];
118 }
119 }
120
121
122 -(void)checkNetworkflow
123 {
124 struct ifaddrs *ifa_list = 0, *ifa;
125 if (getifaddrs(&ifa_list) == -1)
126 {
127 return ;
128 }
129
130 uint32_t iBytes = 0;
131 uint32_t oBytes = 0;
132 uint32_t allFlow = 0;
133 uint32_t wifiIBytes = 0;
134 uint32_t wifiOBytes = 0;
135 uint32_t wifiFlow = 0;
136 uint32_t wwanIBytes = 0;
137 uint32_t wwanOBytes = 0;
138 uint32_t wwanFlow = 0;
139 // struct timeva l32 time;
140
141 for (ifa = ifa_list; ifa; ifa = ifa->ifa_next)
142 {
143 if (AF_LINK != ifa->ifa_addr->sa_family)
144 continue;
145
146 if (!(ifa->ifa_flags & IFF_UP) && !(ifa->ifa_flags & IFF_RUNNING))
147 continue;
148
149 if (ifa->ifa_data == 0)
150 continue;
151
152 // network flow
153 if (strncmp(ifa->ifa_name, "lo", 2))
154 {
155 struct if_data *if_data = (struct if_data *)ifa->ifa_data;
156 iBytes += if_data->ifi_ibytes;
157 oBytes += if_data->ifi_obytes;
158 allFlow = iBytes + oBytes;
159 }
160
161 //wifi flow
162 if (!strcmp(ifa->ifa_name, "en0"))
163 {
164 struct if_data *if_data = (struct if_data *)ifa->ifa_data;
165 wifiIBytes += if_data->ifi_ibytes;
166 wifiOBytes += if_data->ifi_obytes;
167 wifiFlow = wifiIBytes + wifiOBytes;
168 }
169
170 //3G and gprs flow
171 if (!strcmp(ifa->ifa_name, "pdp_ip0"))
172 {
173 struct if_data *if_data = (struct if_data *)ifa->ifa_data;
174 wwanIBytes += if_data->ifi_ibytes;
175 wwanOBytes += if_data->ifi_obytes;
176 wwanFlow = wwanIBytes + wwanOBytes;
177 }
178 }
179 freeifaddrs(ifa_list);
180
181
182 if (_iBytes != 0) {
183 self.receivedNetworkSpeed = [[self bytesToAvaiUnit:iBytes - _iBytes] stringByAppendingString:@"/s"];
184 [[NSNotificationCenter defaultCenter] postNotificationName:kNetworkReceivedSpeedNotification object:@{@"received":self.receivedNetworkSpeed}];
185 }
186
187 _iBytes = iBytes;
188
189 if (_oBytes != 0) {
190 self.sendNetworkSpeed = [[self bytesToAvaiUnit:oBytes - _oBytes] stringByAppendingString:@"/s"];
191 [[NSNotificationCenter defaultCenter] postNotificationName:kNetworkSendSpeedNotification object:@{@"send":self.sendNetworkSpeed}];
192 }
193 _oBytes = oBytes;
194 }
195 @end
|