I'm checking my users data consumption using the method below, taken from here. It's working well most of the time, but for some users it's returning a negative value. In other words the WWANReceived is negative.
How can that be? Is there a fix?
+ (NSArray *)getDataCounters {
BOOL success;
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
const struct if_data *networkStatisc;
int WiFiSent = 0;
int WiFiReceived = 0;
int WWANSent = 0;
int WWANReceived = 0;
NSString *name = [[NSString alloc]init];
// getifmaddrs
success = getifaddrs(&addrs) == 0;
if (success)
{
cursor = addrs;
while (cursor != NULL)
{
name = [NSString stringWithFormat:#"%s",cursor->ifa_name];
// names of interfaces: en0 is WiFi ,pdp_ip0 is WWAN
if (cursor->ifa_addr->sa_family == AF_LINK)
{
if ([name hasPrefix:#"en"])
{
networkStatisc = (const struct if_data *) cursor->ifa_data;
WiFiSent += networkStatisc->ifi_obytes;
WiFiReceived += networkStatisc->ifi_ibytes;
}
if ([name hasPrefix:#"pdp_ip"])
{
networkStatisc = (const struct if_data *) cursor->ifa_data;
WWANSent += networkStatisc->ifi_obytes;
WWANReceived += networkStatisc->ifi_ibytes;
}
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
return [NSArray arrayWithObjects:[NSNumber numberWithInt:WiFiSent], [NSNumber numberWithInt:WiFiReceived],[NSNumber numberWithInt:WWANSent],[NSNumber numberWithInt:WWANReceived], nil];
}
Maybe you've already solved this I was just testing the same example and came upon this.
You have to change the type from int to long long to handle bigger values. What you're seeing is integer overflow that happens after 2GB of traffic.
Related
I want to get the mac Address,IP Address,Host Name, device Name And Brand Name of the devices which are connected to my wifi router.I will Get all these except the host name.
I have tried MMLAnscan,AFNetworking,LANScanMaster,etc it will provide me all the details except host name
+(NSString *)getHostFromIPAddress:(NSString*)ipAddress {
struct addrinfo *result = NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_NUMERICHOST;
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
//"www.kame.net", "http"
int errorStatus = getaddrinfo([ipAddress cStringUsingEncoding:NSUTF8StringEncoding], NULL, &hints, &result);
//NSUTF8StringEncoding instead of NSASCIIStringEncoding
if (errorStatus != 0) {
return nil;
}
CFDataRef addressRef = CFDataCreate(NULL, (UInt8 *)result->ai_addr, result->ai_addrlen);
if (addressRef == nil) {
return nil;
}
freeaddrinfo(result);
CFHostRef hostRef = CFHostCreateWithAddress(kCFAllocatorDefault, addressRef);
if (hostRef == nil) {
return nil;
}
CFRelease(addressRef);
BOOL succeeded = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL);
if (!succeeded) {
return nil;
}
NSMutableArray *hostnames = [NSMutableArray array];
CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
for (int currentIndex = 0; currentIndex < [(__bridge NSArray *)hostnamesRef count]; currentIndex++) {
[hostnames addObject:[(__bridge NSArray *)hostnamesRef objectAtIndex:currentIndex]];
NSLog(#"hostt:%#",hostnames);
}
NSLog(#"hostname:%#",hostnames[0]);
return hostnames[0];
}
I want hostnames of the devices which are connected to my wifi.
I want to know is it possible in iOS to get the data usage by specific WIFI even when app is not running. Is there any API which can be used for this to get result?
To know the total WIFI I used following code:
- (NSArray *)getDataCounters
{
BOOL success;
struct ifaddrs *addrs;
const struct ifaddrs *cursor;
const struct if_data *networkStatisc;
int WiFiSent = 0;
int WiFiReceived = 0;
int WWANSent = 0;
int WWANReceived = 0;
NSString *name=[[NSString alloc]init];
success = getifaddrs(&addrs) == 0;
if (success)
{
cursor = addrs;
while (cursor != NULL)
{
name=[NSString stringWithFormat:#"%s",cursor->ifa_name];
//NSLog(#"ifa_name %s == %#\n", cursor->ifa_name,name);
// names of interfaces: en0 is WiFi ,pdp_ip0 is WWAN
if (cursor->ifa_addr->sa_family == AF_LINK)
{
if ([name hasPrefix:#"en"])
{
networkStatisc = (const struct if_data *) cursor->ifa_data;
WiFiSent+=networkStatisc->ifi_obytes;
WiFiReceived+=networkStatisc->ifi_ibytes;
// NSLog(#"WiFiSent %d ==%d",WiFiSent,networkStatisc->ifi_obytes);
// NSLog(#"WiFiReceived %d ==%d",WiFiReceived,networkStatisc->ifi_ibytes);
}
if ([name hasPrefix:#"pdp_ip"])
{
networkStatisc = (const struct if_data *) cursor->ifa_data;
WWANSent+=networkStatisc->ifi_obytes;
WWANReceived+=networkStatisc->ifi_ibytes;
// NSLog(#"WWANSent %d ==%d",WWANSent,networkStatisc->ifi_obytes);
// NSLog(#"WWANReceived %d ==%d",WWANReceived,networkStatisc->ifi_ibytes);
}
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
NSLog(#"%#",[NSArray arrayWithObjects:[NSNumber numberWithInt:(WiFiSent)/1000000], [NSNumber numberWithInt:(WiFiReceived)/1000000],[NSNumber numberWithInt:(WWANSent)/1000000],[NSNumber numberWithInt:(WWANReceived)/1000000], nil]);
return [NSArray arrayWithObjects:[NSNumber numberWithInt:(WiFiSent)/1000000], [NSNumber numberWithInt:(WiFiReceived)/1000000],[NSNumber numberWithInt:(WWANSent)/1000000],[NSNumber numberWithInt:(WWANReceived)/1000000], nil];
}
Please help me with this.
I do small iPhone app and I need to get IP range and iterate through it with objective C. I can get local IP, netmask. Also I have found on SO solution how to get Broadcast address. But how can I get also Network address? By knowing Network address what is first in the local network and Broadcast address what is last in the local network I would like to iterate all IP from that range. Simply call it and see response. How can I do that?
Solution to get Broadcast from https://stackoverflow.com/a/21077257
#include <net/ethernet.h>
#include <arpa/inet.h>
NSString *localIPAddress = #"192.168.1.10";
NSString *netmaskAddress = #"255.255.192.0";
// Strings to in_addr:
struct in_addr localAddr;
struct in_addr netmaskAddr;
inet_aton([localIPAddress UTF8String], &localAddr);
inet_aton([netmaskAddress UTF8String], &netmaskAddr);
// The broadcast address calculation:
localAddr.s_addr |= ~(netmaskAddr.s_addr);
// in_addr to string:
NSString *broadCastAddress = [NSString stringWithUTF8String:inet_ntoa(localAddr)];
Update: from netmaskAddress I can get number of hosts in the network. I only need to work with IPs. The question now is how can I get next IP from the given? For example I have
NSString *ip = "192.168.1.5"
How can I get "192.168.1.6" with objective C?
I do not recommend do bit operations on this kind of IP's (in_addr) because if you will take a look inside the bytes are reverse ordered.
The code below is printing the device ip, network ip, netmask and broadcast address and all ip's in network range. It might be helpful. Enjoy!
NetworkInformation *network = [[NetworkInformation alloc] init];
NSLog(#"%#", network);
for(NSString *ip in network.ipsInRange){
NSLog(#"ip: %#", ip);
}
NetworkInformation.h
#import <Foundation/Foundation.h>
#interface NetworkInformation : NSObject
#property (nonatomic, retain) NSString *deviceIP;
#property (nonatomic, retain) NSString *netmask;
#property (nonatomic, retain) NSString *address;
#property (nonatomic, retain) NSString *broadcast;
#property (nonatomic, retain) NSArray *ipsInRange;
- (void)updateData;
- (NSString *)description;
#end
NetworkInformation.m
#import "NetworkInformation.h"
#import <arpa/inet.h>
#import <ifaddrs.h>
#implementation NetworkInformation
- (id)init {
self = [super init];
if (self) {
[self updateData];
}
return self;
}
-(void)updateData {
[self updateDataFromWifiNetwork];
self.address = [self getNetworkAddress];
self.ipsInRange = [self getIPsInRange];
}
- (void)updateDataFromWifiNetwork {
self.deviceIP = nil;
self.netmask = nil;
self.broadcast = nil;
struct ifaddrs *interfaces = NULL;
struct ifaddrs *temp_addr = NULL;
int success = 0;
success = getifaddrs(&interfaces);
if (success == 0){
temp_addr = interfaces;
while(temp_addr != NULL){
if(temp_addr->ifa_addr->sa_family == AF_INET){
if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:#"en0"]){
self.deviceIP = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
self.netmask = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_netmask)->sin_addr)];
self.broadcast = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];
}
}
temp_addr = temp_addr->ifa_next;
}
}
freeifaddrs(interfaces);
if(!self.deviceIP || !self.netmask){
NSLog(#"error in updateDataFromWifiNetwork, device ip: %# netmask: %#", self.deviceIP, self.netmask);
}
}
-(NSString*)getNetworkAddress {
if(!self.deviceIP || !self.netmask){
return nil;
}
unsigned int address = [self convertSymbolicIpToNumeric:self.deviceIP];
address &= [self convertSymbolicIpToNumeric:self.netmask];
return [self convertNumericIpToSymbolic:address];
}
-(NSArray*)getIPsInRange {
unsigned int address = [self convertSymbolicIpToNumeric:self.address];
unsigned int netmask = [self convertSymbolicIpToNumeric:self.netmask];
NSMutableArray *result = [[NSMutableArray alloc] init];
int numberOfBits;
for (numberOfBits = 0; numberOfBits < 32; numberOfBits++) {
if ((netmask << numberOfBits) == 0){
break;
}
}
int numberOfIPs = 0;
for (int n = 0; n < (32 - numberOfBits); n++) {
numberOfIPs = numberOfIPs << 1;
numberOfIPs = numberOfIPs | 0x01;
}
for (int i = 1; i < (numberOfIPs) && i < numberOfIPs; i++) {
unsigned int ourIP = address + i;
NSString *ip = [self convertNumericIpToSymbolic:ourIP];
[result addObject:ip];
}
return result;
}
-(NSString*)convertNumericIpToSymbolic:(unsigned int)numericIP {
NSMutableString *sb = [NSMutableString string];
for (int shift = 24; shift > 0; shift -= 8) {
[sb appendString:[NSString stringWithFormat:#"%d", (numericIP >> shift) & 0xff]];
[sb appendString:#"."];
}
[sb appendString:[NSString stringWithFormat:#"%d", (numericIP & 0xff)]];
return sb;
}
-(unsigned int)convertSymbolicIpToNumeric:(NSString*)symbolicIP {
NSArray *st = [symbolicIP componentsSeparatedByString: #"."];
if (st.count != 4){
NSLog(#"error in convertSymbolicIpToNumeric, splited string count: %lu", st.count);
return 0;
}
int i = 24;
int ipNumeric = 0;
for (int n = 0; n < st.count; n++) {
int value = [(NSString*)st[n] intValue];
if (value != (value & 0xff)) {
NSLog(#"error in convertSymbolicIpToNumeric, invalid IP address: %#", symbolicIP);
return 0;
}
ipNumeric += value << i;
i -= 8;
}
return ipNumeric;
}
-(NSString*)description {
return [NSString stringWithFormat: #"\nip:%#\nnetmask:%#\nnetwork:%#\nbroadcast:%#", self.deviceIP, self.netmask, self.address, self.broadcast];
}
#end
What is the best practice to use global variables in Objective-C?
Right now I have a class .h/.m with all of the global variables and where common functions is declared like so:
.h
BOOL bOne;
NSInteger iOne;
BOOL bTwo;
BOOL nThreee;
id NilOrValue(id aValue);
BOOL NSStringIsValidEmail(NSString *email);
BOOL NSStringIsValidName(NSString *name);
BOOL NSStringIsVaildUrl ( NSString * candidate );
BOOL NSStringIsValidPhoneNumber( NSString *phoneNumber );
NSString *displayErrorCode( NSError *anError );
NSString *MacAdress ();
NSString* md5( NSString *str );
#define IS_IPHONE ( [[[UIDevice currentDevice] model] isEqualToString:#"iPhone"] )
#define IS_WIDESCREEN (fabs((double)[[UIScreen mainScreen] bounds].size.height - (double) 568) < DBL_EPSILON)
#define IS_IPHONE_5 ( IS_WIDESCREEN )
#define kSettings [NSUserDefaults standardUserDefaults];
#define EMPTYIFNIL(foo) ((foo == nil) ? #"" : foo)
.m
BOOL bOne = NO;
NSInteger iOne = 0;
BOOL bTwo = NO;
BOOL nThreee = NO;
id NilOrValue(id aValue) {
if ((NSNull *)aValue == [NSNull null]) {
return nil;
}
else {
return aValue;
}
}
NSString* md5( NSString *str )
{
// Create pointer to the string as UTF8
const char *ptr = [str UTF8String];
// Create byte array of unsigned chars
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
// Create 16 byte MD5 hash value, store in buffer
CC_MD5(ptr, (CC_LONG)strlen(ptr), md5Buffer);
// Convert MD5 value in the buffer to NSString of hex values
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:#"%02x",md5Buffer[i]];
return output;
}
BOOL NSStringIsVaildUrl (NSString * candidate) {
NSString *urlRegEx =
#"(http|https)://((\\w)*|([0-9]*)|([-|_])*)+([\\.|/]((\\w)*|([0-9]*)|([-|_])*))+";
NSPredicate *urlTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", urlRegEx];
return [urlTest evaluateWithObject:candidate];
}
BOOL NSStringIsValidEmail(NSString *email) {
NSString *emailRegex = #"[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", emailRegex];
if (email.length == 0) {
return YES;
}else {
if (![emailTest evaluateWithObject:email]) {
return NO;
}else {
return YES;
}
}
}
BOOL NSStringIsValidName(NSString *name) {
NSString *nameRegex = #"^([a-zA-Z'-]+)$";
NSPredicate *nameTest = [NSPredicate predicateWithFormat:#"SELF MATCHES %#", nameRegex];
if (name.length == 0) {
return YES;
}else {
if (![nameTest evaluateWithObject:name]) {
return NO;
} else {
return YES;
}
}
}
BOOL NSStringIsValidPhoneNumber(NSString *phoneNumber) {
NSError *error = NULL;
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypePhoneNumber error:&error];
NSRange inputRange = NSMakeRange(0, [phoneNumber length]);
NSArray *matches = [detector matchesInString:phoneNumber options:0 range:inputRange];
// no match at all
if ([matches count] == 0) {
return NO;
}
// found match but we need to check if it matched the whole string
NSTextCheckingResult *result = (NSTextCheckingResult *)[matches objectAtIndex:0];
if ([result resultType] == NSTextCheckingTypePhoneNumber && result.range.location == inputRange.location && result.range.length == inputRange.length) {
// it matched the whole string
return YES;
}
else {
// it only matched partial string
return NO;
}
}
NSString *MacAdress () {
int mgmtInfoBase[6];
char *msgBuffer = NULL;
size_t length;
unsigned char macAddress[6];
struct if_msghdr *interfaceMsgStruct;
struct sockaddr_dl *socketStruct;
NSString *errorFlag = NULL;
// Setup the management Information Base (mib)
mgmtInfoBase[0] = CTL_NET; // Request network subsystem
mgmtInfoBase[1] = AF_ROUTE; // Routing table info
mgmtInfoBase[2] = 0;
mgmtInfoBase[3] = AF_LINK; // Request link layer information
mgmtInfoBase[4] = NET_RT_IFLIST; // Request all configured interfaces
// With all configured interfaces requested, get handle index
if ((mgmtInfoBase[5] = if_nametoindex("en0")) == 0)
errorFlag = #"if_nametoindex failure";
else
{
// Get the size of the data available (store in len)
if (sysctl(mgmtInfoBase, 6, NULL, &length, NULL, 0) < 0)
errorFlag = #"sysctl mgmtInfoBase failure";
else
{
// Alloc memory based on above call
if ((msgBuffer = malloc(length)) == NULL)
errorFlag = #"buffer allocation failure";
else
{
// Get system information, store in buffer
if (sysctl(mgmtInfoBase, 6, msgBuffer, &length, NULL, 0) < 0)
errorFlag = #"sysctl msgBuffer failure";
}
}
}
// Befor going any further...
if (errorFlag != NULL)
{
NSLog(#"Error: %#", errorFlag);
free(msgBuffer);
return errorFlag;
}
// Map msgbuffer to interface message structure
interfaceMsgStruct = (struct if_msghdr *) msgBuffer;
// Map to link-level socket structure
socketStruct = (struct sockaddr_dl *) (interfaceMsgStruct + 1);
// Copy link layer address data in socket structure to an array
memcpy(&macAddress, socketStruct->sdl_data + socketStruct->sdl_nlen, 6);
// Read from char array into a string object, into traditional Mac address format
NSString *macAddressString = [NSString stringWithFormat:#"%02X:%02X:%02X:%02X:%02X:%02X",
macAddress[0], macAddress[1], macAddress[2],
macAddress[3], macAddress[4], macAddress[5]];
NSLog(#"Mac Address: %#", macAddressString);
// Release the buffer memory
free(msgBuffer);
return macAddressString;
}
Is this a bad solution? If yes how would I manage to use my global variables in the best way?
Global variable always cause problem but in some scenario it is useful there are two type global variable we required one are constant second are those could change there value...
the recommendation is to create immutable global variables instead of in-line string constants (hard to refactor and no compile-time checking) or #defines (no compile-time checking). Here's how you might do so...
in MyConstants.h:
extern NSString * const MyStringConstant;
in MyConstants.m:
NSString * const MyStringConstant = #"MyString";
then in any other .m file:
#import "MyConstants.h"
...
[someObject someMethodTakingAString:MyStringConstant];
...
This way, you gain compile-time checking that you haven't mis-spelled a string constant, you can check for pointer equality rather than string equality[1] in comparing your constants, and debugging is easier, since the constants have a run-time string value.
for mutable variables the safe way is adopting the singalton pattern
#interface VariableStore : NSObject
{
// Place any "global" variables here
}
// message from which our instance is obtained
+ (VariableStore *)sharedInstance;
#end
#implementation VariableStore
+ (VariableStore *)sharedInstance
{
// the instance of this class is stored here
static VariableStore *myInstance = nil;
// check to see if an instance already exists
if (nil == myInstance) {
myInstance = [[[self class] alloc] init];
// initialize variables here
}
// return the instance of this class
return myInstance;
}
#end
One task of my program is to scan local wi-fi network for any devices/computers in same network. I found solution to get all working devices IPs, but did not managed to get names of them. I did not find any clue to solve this problem.
Any suggestions?
In order to perform a reverse DNS lookup, you need to call the CFHostGetNames function, like this:
+ (NSArray *)hostnamesForIPv4Address:(NSString *)address
{
struct addrinfo *result = NULL;
struct addrinfo hints;
memset(&hints, 0, sizeof(hints));
hints.ai_flags = AI_NUMERICHOST;
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = 0;
int errorStatus = getaddrinfo([address cStringUsingEncoding:NSASCIIStringEncoding], NULL, &hints, &result);
if (errorStatus != 0) {
return nil;
}
CFDataRef addressRef = CFDataCreate(NULL, (UInt8 *)result->ai_addr, result->ai_addrlen);
if (addressRef == nil) {
return nil;
}
freeaddrinfo(result);
CFHostRef hostRef = CFHostCreateWithAddress(kCFAllocatorDefault, addressRef);
if (hostRef == nil) {
return nil;
}
CFRelease(addressRef);
BOOL succeeded = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL);
if (!succeeded) {
return nil;
}
NSMutableArray *hostnames = [NSMutableArray array];
CFArrayRef hostnamesRef = CFHostGetNames(hostRef, NULL);
for (int currentIndex = 0; currentIndex < [(__bridge NSArray *)hostnamesRef count]; currentIndex++) {
[hostnames addObject:[(__bridge NSArray *)hostnamesRef objectAtIndex:currentIndex]];
}
return hostnames;
}
BOOL succeeded = CFHostStartInfoResolution(hostRef, kCFHostNames, NULL); Now I encounter that always failed at this line, and I tried to use getnameinfo function, it is still can't get the hostname