1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

how to find mac address using xcode

Discussion in 'Mac Programming' started by chidambaram, Apr 21, 2009.

  1. macrumors member


    I am working in Mac OS 10.4 and xcode 2.5

    I want to find mac address using xcode. How can i find that?

    Thanks in advance...
  2. macrumors G5


    There is no easy way. In Terminal, type "man ifconfig". Read the output, compare it with what System Preferences/Network/Ethernet shows, see where one MAC address turns up. You'll need to start the tool from your application, grab its output, and interpret it.

    Many Macintoshes have more than one MAC address. Some might not have any MAC address. So what do you need this information for?
  3. macrumors 68040


  4. macrumors member


    There are many ways to do it, the easiest way is to use a NSTask.

    NSPipe *outPipe = [NSPipe pipe];
    NSTask* theTask = [[NSTask alloc] init];
    NSString *string;
    NSString *s;
    //Built-in ethernet
    [theTask setStandardOutput:outPipe];
    [theTask setStandardError:outPipe];
    [theTask setLaunchPath:@"/sbin/ifconfig"];
    [theTask setCurrentDirectoryPath:@"~/"];
    [theTask setArguments:[NSArray arrayWithObjects:@"en0", nil]];
    [theTask launch];
    [theTask waitUntilExit];
    string = [[NSString alloc] initWithData:[[outPipe fileHandleForReading] readDataToEndOfFile] encoding:NSUTF8StringEncoding];
    if (![string isEqualToString:@"ifconfig: interface en0 does not exist"]) {
    	s = string;
    	NSRange f;
    	f = [s rangeOfString:@"ether "];
    	if (f.location != NSNotFound) {
    		s = [s substringFromIndex:f.location + f.length];
    		string = [s substringWithRange:NSMakeRange(0, 17)];
    	[ethernet setStringValue:string];
    the other way would be to use getifaddrs, a carbon function. I don't have an example for this, but I can make one if you really want one.
  5. macrumors 68040


    The link i posted has a getifaddrs example in there already. I guess i always prefer a system function vs. parsing command line output, but maybe that's just me.

  6. macrumors member

    Thanks for all replies...

    How can i found the MAC address using java 1.4
  7. macrumors 68040


    If you are truly stuck on 1.4, you're going to need to write a native program (i.e. a C program as described/linked above) that will get the list of MAC addresses, then run that and read up the results. Alternatively, though more complex, you could call into a C subroutine using JNI, but the benefit to doing so is likely dwarfed by the complexity.

    If you have access to 1.6, java.net.NetworkInterface allows an easy means of getting this information without breaking out of the JVM.

  8. macrumors 6502a

    Below is an example I just wrote up using IOKit. While it's not Java, this example might be useful for anyone else looking for this information.

    Save the below code as "MacAddr.m" and compile it using:
    gcc -framework "Foundation" -framework "IOKit" -o MacAddr MacAddr.m

    One important thing to note is that the CF* and NS* classes are toll-free bridged. That is, if you have some CFStringRef, for example, you can just typecast it to NSString* and use it as you would an NSString. This also means the same retain/release requirements apply.
    #import <Foundation/Foundation.h>
    #include <IOKit/IOKitLib.h>
    #include <IOKit/network/IOEthernetInterface.h>
    #include <IOKit/network/IOEthernetController.h>
    static NSDictionary* GetMACAddresses( io_iterator_t netIterator );
    static kern_return_t FindNetworkInterfaces( io_iterator_t *services );
    static NSString* bytesToHexString( NSData* data );
    int main (int argc, const char * argv[]) {
      io_iterator_t intfIterator;
      kern_return_t kernResult = KERN_FAILURE;
      NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
      NSLog(@"Detecting Network Interfaces...");
      kernResult = FindNetworkInterfaces( &intfIterator );
      if( KERN_SUCCESS != kernResult ) {
        printf( "findNetworkInterfaces failed\n" );
      } else {
        NSLog( @"Found one of more valid interfaces. Extracting MAC addresses..." );
        NSDictionary* intfDictionary = GetMACAddresses( intfIterator );
        for( id key in intfDictionary ) {
          NSLog( @"  %@  =>  %@", key, [intfDictionary objectForKey:key] );
        IOObjectRelease( intfIterator );
      [pool drain];
      return 0;
    /* Search through each of the Network interfaces identified
     *  in the netIterator and pull out the MAC address and the BSD
     *  name of the interface. Then convert the raw MAC address into
     *  a readable string and return an NSDictionary with a mapping of
     *  BSD Name (NSString*) => MAC Address (NSString*) for each interface
    static NSDictionary* GetMACAddresses( io_iterator_t netIterator ) {
      NSMutableDictionary*    etherDictionary = nil;
      kern_return_t           kernResult = KERN_FAILURE;
      io_object_t             interfaceService;
      io_object_t             controllerService;
      while( interfaceService = IOIteratorNext( netIterator ) ) {
        CFTypeRef MACAddrAsCFData = NULL;
        CFTypeRef BSDNameAsCFString = NULL;
        kernResult = IORegistryEntryGetParentEntry( interfaceService,
                                                    &controllerService );
        if( KERN_SUCCESS != kernResult ) {
          printf( "IORegistryEntryGetParentEntry failed with 0x%08x\n", kernResult );
        } else {
          MACAddrAsCFData = IORegistryEntryCreateCFProperty( controllerService,
                                                             0 );
          BSDNameAsCFString = IORegistryEntryCreateCFProperty( interfaceService,
                                                               CFSTR("BSD Name"),
                                                               0 );
          if( MACAddrAsCFData && BSDNameAsCFString ) {
            if( nil == etherDictionary ) {
              etherDictionary = [[NSMutableDictionary alloc] init]; 
            [etherDictionary setObject:bytesToHexString((NSData*)MACAddrAsCFData)
          if( nil != BSDNameAsCFString ) {
                CFRelease( BSDNameAsCFString );
          if( nil != MACAddrAsCFData ) {
                CFRelease( MACAddrAsCFData );
      return (nil == etherDictionary) ? nil : (NSDictionary*)[etherDictionary autorelease];
    /* Search through the IOServicePlane and find any services that
     *  represent an IOEthernetInterface. If you wanted to find a
     *  MAC address for a specific interface you could replace the
     *  IOServiceMatching calls with IOBSDNameMatching
    static kern_return_t FindNetworkInterfaces( io_iterator_t *services ) {
      CFMutableDictionaryRef  matchClasses = NULL;
      kern_return_t           kernResult = KERN_FAILURE;
      mach_port_t             machPort;
      kernResult = IOMasterPort( MACH_PORT_NULL, &machPort );
      if( KERN_SUCCESS != kernResult ) {
        printf( "IOMasterPort failed: %d\n", kernResult );
      matchClasses = IOServiceMatching( kIOEthernetInterfaceClass );
      if( NULL == matchClasses ) {
        printf( "IOServiceMatching returned a NULL dictionary" );
      kernResult = IOServiceGetMatchingServices( machPort, matchClasses, services );
      if( KERN_SUCCESS != kernResult ) {
        printf( "IOServiceGetMatchingServices failed: %d\n", kernResult );
      return kernResult;
    static NSString* bytesToHexString( NSData* data ) {
      NSMutableString*  result = [[NSMutableString alloc] initWithCapacity: [data length] << 1];
      UInt8*  mbytes = (UInt8*)[data bytes];
      char    hBytes[8] = {'\0'};
      int     i = 0;
      for( ; i < [data length]; i++ ) {
        snprintf( hBytes, 3, "%02X", mbytes[ i ] );
        if( 0 == i ) {
          [result appendFormat:@"%s", hBytes];
        } else {
          [result appendFormat:@":%s", hBytes];
      return (NSString*)[result autorelease];

Share This Page