The question is how can I get routing table on MACOSX?
I don’t mean netstat -nr. I mean how to do it programmatically using C.
The first of all I have downloaded netstat source codes from opensource.apple.com.
I have found void mroutepr(void) function in mroute.c.
This function looks like function which get routing table but I am not sure.
There is a array declaration: struct vif viftable[CONFIG_MAXVIFS];
But when I tried to compile mroutepr I revealed that struct vif is not declared in /usr/include/netinet/ip_mroute.h I have added all necessary includes. I have checked it seven times :))
Then I check xnu kernel source code. I have found this structute in xnu kernel, in this file: xnu/bsd/netinet/ip_mroute.h. There was complete definition of struct vif.
It seems that this structure available only in kernel mode.
I am puzzled.
How can struct vif be declared only for kernel code? How netstat utility works?
Everythig above is incorrect :)))
The solution is in route.c file.
ntreestuff(void) function is entry point for getting routing table.
Then in np_rtentry(rtm) function we print table to the console.
static void ntreestuff(void)
{
size_t needed;
int mib[6];
char *buf, *next, *lim;
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;
np_rtentry(rtm);
}
}