Pages

September 11, 2013

Check if a string is a valid MAC address

How to test if a string is a valid MAC address?
You need:
- http://objective-c-functions.blogspot.com/2013/08/check-if-number-is-valid-hex.html


/** Check if a MAC address is valid.

 MAC address must be in the 12:34:56:78:9A:BC format.

 @param mac String representing the MAC address to check.
 @return Returns true if given MAC address is valid, false otherwise.
 @see macAddressWithColonsFromString:
 @see getMacAddressesFromFileAtPath:

 */
+ (BOOL)isValidMacAddress:(NSString *)mac {

    // Must be 17 chars.
    NSInteger len = [mac length];
    if (len != 17) {
        return NO;
    }

    // Let's valide all characters.
    NSString *tempStr;
    if (len == 17) {

        // Loop by couples plus separator (eg: "C6:").
        for (NSInteger i=0; i<=len; i+=3) {

            // Position 0: hex char.
            tempStr = [mac substringWithRange:NSMakeRange(i+0, 1)];
            if (![LMFunctions isHexadecimalNumber:tempStr]) { return NO; }

            // Position 1: hex char.
            tempStr = [mac substringWithRange:NSMakeRange(i+1, 1)];
            if (![LMFunctions isHexadecimalNumber:tempStr]) { return NO; }

            // Position 2: separator.
            if (i+2 < len) // Warning: last separator does not exist.
            {
                tempStr = [mac substringWithRange:NSMakeRange(i+2, 1)];
                if (![tempStr isEqualToString:@":"]) { return NO; }
            }
        }
    }

    return YES;
}



Download the ready-for-use source file (.m) of Check if a string is a valid MAC address

No comments:

Post a Comment