0

I've found Apple's example on how to get the MAC Address of a computer, however, it seems to return it in an array of bytes (or something like that).

For my application, I need it in an NSString (like "00:00:00:00:00"). I'm fairly new to this, and my attempts to convert the CFData (I think) that the sample code seems to return have not been met with success.

I see that in the sample code it will return kernResult. If that has the MAC Address in it, how can I get out of kernResult and into an NSString?

lightbord
  • 143
  • 4
  • Check this question out (it's for iOS, but it can help nonetheless): https://stackoverflow.com/questions/677530/how-can-i-programmatically-get-the-mac-address-of-an-iphone – Tamás Sengel Oct 13 '17 at 17:14
  • Thanks. I'll give this a shot. I saw it was for iOS and disregarded it, as I wasn't aware that this would work on the Mac as well. – lightbord Oct 13 '17 at 17:17

1 Answers1

0

Referring to GetPrimaryMACAddress just write

NSString *macAddress = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", 
        MACAddress[0], MACAddress[1], MACAddress[2], MACAddress[3], MACAddress[4], MACAddress[5]]; 
vadian
  • 274,689
  • 30
  • 353
  • 361
  • I've changed the main function in the sample from `int main(int argc, char *argv[])` to `NSString* getmac()`. Then instead of returning `kernResult`, I have it returning the `NSString` `macAddress`. Then, where I need the string in Obj-C, I just call `getmac()`. This seems to work. However, is this safe (aka not a bad programming practice)? What will the result be if the sample code is unable to retrieve the MAC Address? – lightbord Oct 13 '17 at 17:25
  • Yes you can do that. In case of an error return the error message. But don't forget to release the iterator. – vadian Oct 13 '17 at 17:29
  • doesn't the iterator get released in the sample code (with `(void) IOObjectRelease(intfIterator);`)? I've just copied the sample code to the top of my AppDelegate and made the changes I've mentioned. – lightbord Oct 13 '17 at 17:31
  • Yes it does. It's just a note, because it seems likely to return the values directly from the `if` - `else` branches. – vadian Oct 13 '17 at 17:35