Objective-C : How to fetch the router address?

I tried to fetch the router address this way.

- (NSString *) routerIp {

  NSString *address = @"error";
  struct ifaddrs *interfaces = NULL;
  struct ifaddrs *temp_addr = NULL;
  int success = 0;

  // retrieve the current interfaces - returns 0 on success
  success = getifaddrs(&interfaces);
  if (success == 0)
  {
    // Loop through linked list of interfaces
    temp_addr = interfaces;
    while(temp_addr != NULL)
    {
      if(temp_addr->ifa_addr->sa_family == AF_INET)
      {
        // Check if interface is en0 which is the wifi connection on the iPhone
        if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"])
        {
          // Get NSString from C String //ifa_addr
          address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_dstaddr)->sin_addr)];
        }
      }

      temp_addr = temp_addr->ifa_next;
    }
  }

  // Free memory
  freeifaddrs(interfaces);

  return address;
}

The router address always looks like xxx.xxx.255.255 but it is supposed to look like xxx.xxx.0.1 or something this way...

Is there anything to do to get the valid address?

Thanks for your help!


I've been looking for a way to get the IP address of the default gateway myself. I'm going to focus just on this - I didn't need to get the MAC address of the default router, so this only partially answers the OP's question.

I didn't like the idea of parsing the netstat output. Also, you can't get a default route based on the IP address an interface on your machine has. Any IP address within the same range as yours can be a default gateway - the only rule is that both your IP and the default gateway need to be part of the same subnet.

One more thing I wanted to ensure is to get an IP address of the default gateway even if more than one of my local interfaces has an IP address assigned to it (e.g. I'm connected to the Wifi and to the wired Ethernet at the same time, and both interfaces are up, with an IP address on them). For my application, it doesn't matter which interface the default route is set via (it can be en0, en1, ppp0 or anything else at all).

I think the best (and most Apple-like) way to get that info is to use System Configuration Framework - the links in the post above in this thread pointed me in that direction, but didn't really give much detail as to how to use it, and I didn't find the Apple documentation on it very useful (at least taking into consideration my skill level).

Please mind I'm not very experienced in Objective-C - I'm in the middle of writing an app that I need myself (and which I couldn't find), and for that app I just need the IP address of the default gateway.

So - here's what I'm doing in my app, and it seems to be working fine (plus is much shorter and simpler than most other solutions I found so far:

- (NSString *)defaultRouter {

    SCDynamicStoreRef ds = SCDynamicStoreCreate(kCFAllocatorDefault, CFSTR("myapp"), NULL, NULL);
    CFDictionaryRef dr = SCDynamicStoreCopyValue(ds, CFSTR("State:/Network/Global/IPv4"));
    CFStringRef router = CFDictionaryGetValue(dr, CFSTR("Router"));
    NSString *routerString = [NSString stringWithString:(__bridge NSString *)router];
    CFRelease(dr);
    CFRelease(ds);

    return routerString;
}

Please note that in my app, the above is part of a larger method (I don't actually have a defaultRouter: method in there). Also, I've omitted some of the checks (like [routerString length] and so on) for brevity.

Hopefully someone finds this useful. Please also feel free to fix any errors I might have in the code above - I'm still a newbie!

PS. I got an idea of what to look for when I checked the output of 'scutil', which uses the System Configuration Framework itself:

MacBook:~$ scutil 
> show State:/Network/Global/IPv4
<dictionary> {
  PrimaryInterface : en1
  PrimaryService : <service_id>
  Router : <ipv4_address>
}
> show State:/Network/Global/IPv6
<dictionary> {
  PrimaryInterface : en1
  PrimaryService : <service_id>
  Router : <ipv6_address>
}

Here is some code I wrote to find the routes for the machine. I copied the system calls from the code for netstat. Note that I was strongly recommended against doing this, as these system calls are not a supported API and may change at any time. They recommended I just parse the output of netstat.

CustomRoute.c:

#import "CustomRoute.h"
@implementation CustomRoute

+ (NSMutableArray*) getRoutes
{
    NSMutableArray* routeArray = [NSMutableArray array];
    CustomRoute* route = nil;

    size_t needed;
    int mib[6];
    char *buf, *next, *lim;
    register struct rt_msghdr2 *rtm;

    mib[0] = CTL_NET;
    mib[1] = PF_ROUTE;
    mib[2] = 0;
    mib[3] = 0;
    mib[4] = NET_RT_DUMP2;
    mib[5] = 0;

    if (sysctl(mib, 6, NULL, &needed, NULL, 0) < 0) {
        err(1, "sysctl: net.route.0.0.dump estimate");
    }

    if ((buf = malloc(needed)) == 0) {
        err(2, "malloc(%lu)", (unsigned long)needed);
    }
    if (sysctl(mib, 6, buf, &needed, NULL, 0) < 0) {
        err(1, "sysctl: net.route.0.0.dump");
    }

    lim  = buf + needed;

    for (next = buf; next < lim; next += rtm->rtm_msglen) {
        rtm = (struct rt_msghdr2 *)next;
        route = [self getRoute:rtm];
        if(route != nil)
        {
            [routeArray addObject:route];
        }
    }
    free(buf);
    printf("Total routes: %u\n",    [routeArray count]);
    return routeArray;
}


+ (CustomRoute*) getRoute:(struct rt_msghdr2 *)rtm
{
    //sockaddrs are after the message header
    struct sockaddr* dst_sa = (struct sockaddr *)(rtm + 1);

    CustomRoute* route = nil;

    if(rtm->rtm_addrs & RTA_DST)
    {
        switch(dst_sa->sa_family)
        {
            case AF_INET:
                if(dst_sa->sa_family == AF_INET && !((rtm->rtm_flags & RTF_WASCLONED) && (rtm->rtm_parentflags & RTF_PRCLONING)))
                {
                    route = [[CustomRoute alloc] initWithRtm:rtm];
                }
            break;

        }
    }

    return route;
}

-(void) setAddr:(struct sockaddr*)sa index:(int)rtax_index
{
    if(rtax_index >= 0 && rtax_index < RTAX_MAX)
    {
        memcpy(&(m_addrs[rtax_index]), sa, sizeof(struct sockaddr));
    }

}

-(NSString*) getDestination
{
    return [self getAddrStringByIndex:RTAX_DST];
}

-(NSString*) getNetmask
{
    return [self getAddrStringByIndex:RTAX_NETMASK];
}

-(NSString*) getGateway
{
    return [self getAddrStringByIndex:RTAX_GATEWAY];
}

-(NSString*) getDetails
{
    NSMutableString* result = [[NSMutableString alloc] init];
    [result appendFormat: [NSString stringWithFormat: @"message type: 0x%06x\n", m_rtm.rtm_type]];
    [result appendFormat: [NSString stringWithFormat: @"flags: 0x%06x\n", m_rtm.rtm_flags]];
    [result appendFormat: [NSString stringWithFormat: @"addrs: 0x%06x\n", m_rtm.rtm_addrs]];


    return result;
}


-initWithRtm: (struct rt_msghdr2*) rtm
{
    int i;
    struct sockaddr* sa = (struct sockaddr*)(rtm + 1);


    //copy over the route message
    memcpy(&(m_rtm), rtm, sizeof(struct rt_msghdr2));
    for(i = 0; i < RTAX_MAX; i++)
    {
        [self setAddr:&(sa[i]) index:i];
    }
    return self;
}

- init
{
    memset(m_addrs, 0, sizeof(m_addrs));
    return self;
}

@end


@implementation CustomRoute (Private)

-(NSString*) getAddrStringByIndex: (int)rtax_index
{
    NSString * routeString = nil;
    struct sockaddr* sa = &(m_addrs[rtax_index]);
    int flagVal = 1 << rtax_index;

    if(!(m_rtm.rtm_addrs & flagVal))
    {
        return @"none";
    }


    if(rtax_index >= 0 && rtax_index < RTAX_MAX)
    {
        switch(sa->sa_family)
        {
            case AF_INET:
            {
                struct sockaddr_in* si = (struct sockaddr_in *)sa;
                if(si->sin_addr.s_addr == INADDR_ANY)
                    routeString = @"default";
                else
                    routeString = [NSString stringWithCString:(char *)inet_ntoa(si->sin_addr) encoding:NSASCIIStringEncoding];
            }
            break;

            case AF_LINK:
                {
                    struct sockaddr_dl* sdl = (struct sockaddr_dl*)sa;
                    if(sdl->sdl_nlen + sdl->sdl_alen + sdl->sdl_slen == 0)
                    {
                        routeString = [NSString stringWithFormat: @"link #%d", sdl->sdl_index];
                    }
                    else
                        routeString = [NSString stringWithCString:link_ntoa(sdl) encoding:NSASCIIStringEncoding];
                }
            break;

            default:
                {
                    char a[3 * sa->sa_len];
                    char *cp;
                    char *sep = "";
                    int i;

                    if(sa->sa_len == 0)
                    {
                        routeString = @"empty";
                    }
                    else
                    {
                        a[0] = (char)NULL;
                        for(i = 0, cp = a; i < sa->sa_len; i++)
                        {
                            cp += sprintf(cp, "%s%02x", sep, (unsigned char)sa->sa_data[i]);
                            sep = ":";
                        }
                        routeString = [NSString stringWithCString:a encoding:NSASCIIStringEncoding];
                    }
                }
        }
    }
    return routeString;
}

@end

CustomRoute.h:

#import <Cocoa/Cocoa.h>
#import <net/route.h>
#import <sys/socket.h>
#import <netinet/in.h>
#import <net/if_dl.h>
#import <sys/sysctl.h>

@interface CustomRoute : NSObject {
    struct sockaddr     m_addrs[RTAX_MAX];
    struct rt_msghdr2   m_rtm;
    int                 m_len;      /* length of the sockaddr array */
}

+ (NSMutableArray*) getRoutes;
+ (CustomRoute*) getRoute:(struct rt_msghdr2 *)rtm;

- (void) setAddr:(struct sockaddr*)sa index:(int)rtax_index;

- (NSString*) getDestination;
- (NSString*) getNetmask;
- (NSString*) getGateway;
- initWithRtm: (struct rt_msghdr2*) rtm;


@end