OneGuyInDc
OneGuyInDc

Reputation: 1565

iOS convert IP Address to integer and backwards

Say I have a NSString NSString *myIpAddress = @"192.168.1.1"

I want to convert this to a integer - increment it an then convert it back to NSString.

Does iOS have an easy way to do this other than using bit mask and shifting and sprintf?

Upvotes: 0

Views: 1272

Answers (1)

mattjgalloway
mattjgalloway

Reputation: 34912

Something like this is what I do in my app:

NSArray *ipExplode = [string componentsSeparatedByString:@"."];
int seg1 = [ipExplode[0] intValue];
int seg2 = [ipExplode[1] intValue];
int seg3 = [ipExplode[2] intValue];
int seg4 = [ipExplode[3] intValue];

uint32_t newIP = 0;
newIP |= (uint32_t)((seg1 & 0xFF) << 24);
newIP |= (uint32_t)((seg2 & 0xFF) << 16);
newIP |= (uint32_t)((seg3 & 0xFF) << 8);
newIP |= (uint32_t)((seg4 & 0xFF) << 0);

newIP++;
NSString *newIPStr = [NSString stringWithFormat:@"%u.%u.%u.%u", 
        ((newIP >> 24) & 0xFF), 
        ((newIP >> 16) & 0xFF), 
        ((newIP >> 8) & 0xFF), 
        ((newIP >> 0) & 0xFF)];

Upvotes: 5

Related Questions