简体   繁体   中英

Objective C String Manipulation of an IP Address

I have an NSString that is a local IP Address, and I need to remove the last set of digits on this IP Address and replace with 255. I am doing this to create broadcast packet from the local IP Address.

I have checked all the available string manipulation functions and cannot find a Left function, which would help for this situation.

Basically I want to do this:-

Convert 192.168.1.10 to 192.168.1.255

Edit: Please note the following information for calculating the broadcast address for a network. It is calculated by performing a bitwise OR with the IP Address and the inverted Netmask. You can see a calculator here - http://www.subnet-calculator.com/

Also the actual code on how to calculate the broadcast address is available here - Calculating the Broadcast Address in Objective-C

This was added to avoid any confusion created with my question.

Getting index of a character in NSString with offset & using substring in Objective-C shows you how to find the range of a string within another string, including option of a backwards search. Using that, find the range of @"." (with the NSBackwardsSearch option) within your IP address ipaddr .

Assuming you got the range into a variable named range , range.location is what you need but range.length is not (it's 1, the length of @".") so fix that: range.length = [ipaddr.length] - range.location; .

Finally, use that range to perform a replacement: maskAddress = [ipaddress stringByReplacingCharactersInRange:range withString:@".255"];

Now maskAddr contains the replacement you've described.

NSScanner* scanner = [NSScanner scannerWithString:idAddress];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"."]];
int a, b, c;
[scanner scanInt:&a];
[scanner scanInt:&b];
[scanner scanInt:&c];
NSString* result = [NSString stringWithFormat:@"%d.%d.%d.255", a, b, c];

NSString has -componentsSeparatedByString: which you could use to separate the string into an array (if you specify @“.” as the string), change the array, then put them back together with NSArray's -componentsJoinedByString:

Or you could use NSString's -rangeOfString:@“.” options:NSBackwardsSearch to find where the last “.” is, and then pull apart the string with substringToIndex: and append your @“255”.

Or you could use NSString's -stringByReplacingOccurrencesOfString:(NSString *)target withString:(NSString *)replacement options:(NSStringCompareOptions)options range:(NSRange)searchRange and specify that you're doing a RegEx, but that'd be harder.

you can use a method substringToIndex on NSSring object like they did here

and then append a string or use NSStringWithFormat to create a new one

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM