Usage of global variables in Objective-C - ios

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

Related

how to re-encode data from CFFTPCreateParsedResourceListing function?

i try to communicate with FTP server using CFNetwork.framework.
using CFFTP API(CFWriteStreamCreateWithFTPURL function), i get a NSData of specific URL.
then i start to parse the NSData with CFFTPCreateParsedResourceListing function, it gives me poorly encoded filenames.(when the file name is Korean)
all character in Korean is converted to question mark(?).
how can i fix this? please give me some advice. thank you in advance.
NSMutableArray * newEntries;
NSUInteger offset;
newEntries = [NSMutableArray array];
assert(newEntries != nil);
offset = 0;
do {
CFIndex bytesConsumed;
CFDictionaryRef thisEntry;
thisEntry = NULL;
assert(offset <= [self.listData length]);
bytesConsumed = CFFTPCreateParsedResourceListing(NULL, &((const uint8_t *) self.listData.bytes)[offset], (CFIndex) ([self.listData length] - offset), &thisEntry);
if (bytesConsumed > 0) {
if (thisEntry != NULL) {
NSDictionary * entryToAdd;
entryToAdd = [self entryByReencodingNameInEntry:(__bridge NSDictionary *) thisEntry encoding:NSUTF8StringEncoding];
[newEntries addObject:entryToAdd];
}
offset += (NSUInteger) bytesConsumed;
}
if (thisEntry != NULL) {
CFRelease(thisEntry);
}
if (bytesConsumed == 0) {
break;
} else if (bytesConsumed < 0) {
[self stopReceiveWithStatus:#"Listing parse failed"];
break;
}
} while (YES);
below code is entryByReencodingNameInEntry method
NSDictionary * result;
NSString * name;
NSData * nameData;
NSString * newName;
newName = nil;
// Try to get the name, convert it back to MacRoman, and then reconvert it
// with the preferred encoding.
name = [entry objectForKey:(id) kCFFTPResourceName];
if (name != nil) {
assert([name isKindOfClass:[NSString class]]);
nameData = [name dataUsingEncoding:NSMacOSRomanStringEncoding];
if (nameData != nil) {
newName = [[NSString alloc] initWithData:nameData encoding:newEncoding];
}
}
if (newName == nil) {
assert(NO); // in the debug builds, if this fails, we should investigate why
result = (NSDictionary *) entry;
} else {
NSMutableDictionary * newEntry;
newEntry = [entry mutableCopy];
assert(newEntry != nil);
[newEntry setObject:newName forKey:(id) kCFFTPResourceName];
result = newEntry;
}
return result;
for example,
if a folder has 3 files
애플.txt, 삼성.txt, 테스트.txt -> converted to ??.txt, ??.txt, ???.txt

getting error in the SOLStumbler for wifi list

In my app I need to get the wifi details, with this I got the connected wifi details, I want to get the wifi list, so I used the private API SOLStumbler, with this I am getting an exc_bad_access error in
apple80211Open(&airportHandle);
actual code is:
NSMutableDictionary *networks; //Key: MAC Address (BSSID)
void *libHandle;
void *airportHandle;
int (*apple80211Open)(void *);
int (*apple80211Bind)(void *, NSString *);
int (*apple80211Close)(void *);
int (*associate)(void *, NSDictionary*, NSString*);
int (*apple80211Scan)(void *, NSArray **, void *);
- (id)init
{
self = [super init];
networks = [[NSMutableDictionary alloc] init];
libHandle = dlopen("/System/Library/SystemConfiguration/IPConfiguration.bundle/IPConfiguration", RTLD_LAZY);
// libHandle = dlopen("/System/Library/SystemConfiguration/WiFiManager.bundle/WiFiManager", RTLD_LAZY);
// libHandle = dlopen("/System/Library/PrivateFrameworks/MobileWiFi.framework/MobileWiFi", RTLD_LAZY);
char *error;
if (libHandle == NULL && (error = dlerror()) != NULL) {
NSLog(#"err ...r%s",error);
exit(1);
}
else{
NSLog(#"not null");
}
apple80211Open = dlsym(libHandle, "Apple80211Open");
apple80211Bind = dlsym(libHandle, "Apple80211BindToInterface");
apple80211Close = dlsym(libHandle, "Apple80211Close");
apple80211Scan = dlsym(libHandle, "Apple80211Scan");
applecopy= dlsym(libHandle, "Apple80211GetInfoCopy");
apple80211Open(&airportHandle);
apple80211Bind(airportHandle, #"en0");
return self;
}
Above Method not accepted by apple because they are using private API,
Please try to used below method to get the SSID and BSSID without using Private API.
- (id)fetchSSIDInfo {
NSArray *ifs = (__bridge_transfer NSArray *)CNCopySupportedInterfaces();
NSLog(#"Supported interfaces: %#", ifs);
NSDictionary *info;
for (NSString *ifnam in ifs) {
info = (__bridge_transfer NSDictionary *)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
NSLog(#"%# => %#", ifnam, info);
if (info && [info count]) { break; }
}
return info;}

Negative Value data usage on iPhone?

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.

What are some different ways of making an effective email validation method without using regular expression in objective c?

I was requested to do email validation that will check the following conditions without regex(I was asked by the teacher to do it like that):
Check that # exist once in the string
Check that left sub string (left to #) isn't empty
Check that right sub string (right to #) isn't empty
Check that . exist in right sub string (right to #)
Check that left sub sub string isn't empty (right to #, left to .)
Check that right sub sub string's length is at least 2
Here was one of my attempts, wasn't able to make it work...
- (BOOL) checkIfValidEmail{
BOOL helper = NO;
if ([self length] < 6) {
return NO;
}else
{
NSMutableArray *charArray = [NSMutableArray new];
for (int i = 0; i < [self length]; i++) {
NSString *charte = [NSString stringWithFormat:#"%C", [self characterAtIndex:i]];
[charArray addObject:charte];
}
for (int i = 0; i < [self length]; i++) {
NSString *charter = charArray[i];
if ([#"#"isEqualToString:charter] && helper == NO ) {
helper = YES;
}
if ([#"." isEqualToString:charter] && helper == YES) {
helper = YES;
}
}
}
return helper;
}
my attempt
#interface Tester : NSObject
+(BOOL) testForValidMail:(NSString *)mail;
#end
#implementation Tester
+(BOOL)testForValidMail:(NSString *)string
{
NSRange atRange = [string rangeOfString:#"#"];
BOOL b = NO;
if ((atRange.location != NSNotFound) //is `#` present
&& (atRange.location != 0) // and is `#` not at the beginning -> left substring exist
&& (atRange.location != string.length-1) // and not at the end -> right substring exists
&& ([[string componentsSeparatedByString:#"#"] count] == 2)) // and is there only one `#`?
{
// is there a `.` right of the `#`?
NSRange dotRange = [[string substringFromIndex:atRange.length +atRange.location] rangeOfString:#"."];
if((dotRange.location != NSNotFound) // is there a `.` right of `#`
&& (dotRange.location !=0) // and is it not the very next char after `#`
&& ([[string substringFromIndex:[string length]-2] rangeOfString:#"."].location == NSNotFound)) // and the `.` is not the last or second last char
{
b = YES;
}
}
return b;
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSArray *candidates = #[#"m#m.de",
#"m#.de",
#"m#m.e",
#"#m.de",
#"m<at>m.de",
#"mm#mm#mm.de",
#"email#email.email.email.com" //if you are the owner of email.com, you can decide to create this address
];
[candidates enumerateObjectsUsingBlock:^(NSString *mailAdress, NSUInteger idx, BOOL *stop) {
NSLog(#"%#, %#",([Tester testForValidMail:mailAdress]) ? #"YES" : #"NO", mailAdress );
}];
}
return 0;
}
result:
2014-02-14 21:05:49.404 emailcheck[16271:303] YES, m#m.de
2014-02-14 21:05:49.405 emailcheck[16271:303] NO, m#.de
2014-02-14 21:05:49.406 emailcheck[16271:303] NO, m#m.e
2014-02-14 21:05:49.406 emailcheck[16271:303] NO, #m.de
2014-02-14 21:05:49.406 emailcheck[16271:303] NO, m<at>m.de
2014-02-14 21:05:49.407 emailcheck[16271:303] NO, mm#mm#mm.de
2014-02-14 21:05:49.407 emailcheck[16271:303] YES, email#email.email.email.com
I added another check: not more than one #
I rewrote my code as Category on NSString
#interface NSString (EmailAddressTest)
-(BOOL) isValidMailAddress;
#end
#implementation NSString (EmailAddressTest)
-(BOOL)isValidMailAddress
{
NSRange atRange = [self rangeOfString:#"#"];
BOOL b = NO;
if ((atRange.location != NSNotFound) //is `#` present
&& (atRange.location != 0) // and is `#` not at the beginning -> left substring exist
&& (atRange.location != [self length]-1) // and not at the end -> right substring exists
&& ([[self componentsSeparatedByString:#"#"] count] == 2)) // and is there only one `#`?
{
// is there a `.` right of the `#`?
NSRange dotRange = [[self substringFromIndex:atRange.length +atRange.location] rangeOfString:#"."];
if((dotRange.location != NSNotFound) // is there a `.` right of `#`
&& (dotRange.location !=0) // and is it not the very next char after `#`
&& ([[self substringFromIndex:[self length]-2] rangeOfString:#"."].location == NSNotFound)) // and the `.` is not the last or second last char
{
b = YES;
}
}
return b;
}
#end
int main(int argc, const char * argv[])
{
#autoreleasepool {
[#[#"m#m.de", #"m#.de", #"m#m.e", #"#m.de", #"m<at>m.de", #"mm#mm#mm.de"] enumerateObjectsUsingBlock:^(NSString *mailAdress, NSUInteger idx, BOOL *stop) {
NSLog(#"%#, %#",([mailAdress isValidMailAddress]) ? #"YES" : #"NO", mailAdress );
}];
}
return 0;
}

Get ip range with objective C

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

Resources