This function checks if an IP address (either IPv4 or IPv6) is valid.
/** Check if an IP address is valid.
Looks for both IPv4 and IPv6.
Based on: http://stackoverflow.com/questions/1679152/how-to-validate-an-ip-address-with-regular-expression-in-objective-c/10971521#10971521
@param ip IP address as string.
@return Returns true if given IP address is valid, false otherwise.
*/
+ (BOOL)isValidIpAddress:(NSString *)ip {
const char *utf8 = [ip UTF8String];
// Check valid IPv4.
struct in_addr dst;
int success = inet_pton(AF_INET, utf8, &(dst.s_addr));
if (success != 1) {
// Check valid IPv6.
struct in6_addr dst6;
success = inet_pton(AF_INET6, utf8, &dst6);
}
return (success == 1);
}
Download the ready-for-use source file (.m) of Check if a string is a valid IP address (IPv4 and IPv6)
Yes. Link to adf.ly is much much better than link to Stackoverflow.
ReplyDelete