Horhe Garcia
Horhe Garcia

Reputation: 902

Is there function to parse an IP address into 4 integers in iOS?

Something like inet_addr("127.0.0.1")?

Upvotes: 0

Views: 1319

Answers (3)

jamesC
jamesC

Reputation: 422

I think you should probably check out the String Programming Guide. If it is something simple you could just do something like

... [yourSting stringcomponetsSeparatedByString@"."]; //('formatting String Objects' section)

or you could do something envolving scanners from apple's sample code ('Scanners section') so that you can search through the relevant string for what you want:

NSString *string = @"Product: Acme Potato Peeler; Cost: 0.98 73\n\
Product: Chef Pierre Pasta Fork; Cost: 0.75 19\n\
Product: Chef Pierre Colander; Cost: 1.27 2\n";

NSCharacterSet *semicolonSet;
NSScanner *theScanner;
NSString *PRODUCT = @"Product:";
NSString *COST = @"Cost:";
NSString *productName;
float productCost;

NSInteger productSold;
semicolonSet = [NSCharacterSet characterSetWithCharactersInString:@";"];
theScanner = [NSScanner scannerWithString:string];
while ([theScanner isAtEnd] == NO)
{
if ([theScanner scanString:PRODUCT intoString:NULL] &&
[theScanner scanUpToCharactersFromSet:semicolonSet
intoString:&productName] &&
[theScanner scanString:@";" intoString:NULL] &&
[theScanner scanString:COST intoString:NULL] &&
[theScanner scanFloat:&productCost] &&
[theScanner scanInteger:&productSold])
{
NSLog(@"Sales of %@: $%1.2f", productName, productCost * productSold);
}
}

Good Luck

Upvotes: 0

holographix
holographix

Reputation: 2557

You should be calling something like

 inet_pton(AF_INET, "239.255.255.250", &broadcastAddr.sin_addr);

you have to include

  #include <arpa/inet.h>

Upvotes: 0

NeverBe
NeverBe

Reputation: 5038

NSString *ipAddress = [NSString stringWithString:@"127.0.0.1"];

NSArray *results = [ipAddress componentsSeparatedByString:@"."];
if ([results count] == 4) {
    NSLog(@"1 - %d", [[results objectAtIndex:0] intValue]);
    NSLog(@"2 - %d", [[results objectAtIndex:1] intValue]);
    NSLog(@"3 - %d", [[results objectAtIndex:2] intValue]);
    NSLog(@"4 - %d", [[results objectAtIndex:3] intValue]);
} else {
    NSLog(@"not valid ip");
}

Upvotes: 3

Related Questions