I am obtaining the mac(hw) address of an interface using CWNetwork. Now OS X gives me this mac address in the xx:xx:xx:xx:xx:xx format. But if the first digit is 0, OS X will output the address as 4:aa:dd:ee:34:40, instead of 04:aa:dd:ee:34:40.
Now I am trying to take this string 4:aa:dd:ee:34:40 and convert it to 04:aa:dd:ee:34:40 before displaying it. Any idea开发者_C百科s ? APpreciate the help.
You're not calling ether_ntoa(3) yourself, are you? I seem to recall that ether_ntoa is the usual culprit that likes to drop the leading zeros from each octet of the MAC address.
Can you get the raw bytes of MAC address (like the sockaddr_dl->sdl_data, rather than a preformatted string) and then use your own printf-style format string to format it the way you want? Something like "%02x:%02x:%02x:%02x:%02x:%02x" is probably what you want.
I believe the following code does what you want.
NSString *macAddress = @"4:aa:dd:ee:34:40";
NSScanner *scanner = [NSScanner scannerWithString:macAddress];
[scanner setCharactersToBeSkipped:[NSCharacterSet punctuationCharacterSet]];
NSMutableString *result = [NSMutableString stringWithCapacity:[macAddress length]];
while (![scanner isAtEnd]) {
unsigned theValue;
if ([scanner scanHexInt:&theValue]) {
[result appendFormat:@":%02x",theValue];
} else {
[result appendString:@":??"];
}
}
NSLog(@"%@",[result substringFromIndex:1]);
精彩评论