Created
September 19, 2020 14:45
-
-
Save hiroyuki-sato/3d51dc740b222c712b6d9d2320b714c9 to your computer and use it in GitHub Desktop.
check default router interface on macOS.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <sys/sysctl.h> | |
#include <sys/socket.h> | |
#include <net/route.h> | |
#include <netinet/in.h> | |
#include <net/if.h> | |
int main(int argc,char *argv[]){ | |
int mib[6]; | |
size_t needed; | |
char *buf, *next, *lim; | |
struct rt_msghdr2 *rtm; | |
char ifname[IFNAMSIZ + 1]; | |
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){ | |
perror("sysctl"); | |
exit(1); | |
} | |
if((buf = malloc(needed)) == 0 ){ | |
perror("malloc"); | |
exit(1); | |
} | |
if( sysctl(mib, 6, buf, &needed, NULL,0) < 0){ | |
perror("sysctl"); | |
exit(1); | |
} | |
lim = buf + needed; | |
for (next = buf; next < lim; next += rtm->rtm_msglen) { | |
struct sockaddr *sa; | |
rtm = (struct rt_msghdr2 *)next; | |
sa = (struct sockaddr *)(rtm + 1); | |
if(sa->sa_family == AF_INET) { | |
struct sockaddr_in *sin = (struct sockaddr_in *)sa; | |
off_t offset = sizeof(struct sockaddr)*RTA_NETMASK; | |
struct sockaddr_in *mask = (struct sockaddr_in *)sa + offset; | |
/* address: 0.0.0.0/0 */ | |
if( rtm->rtm_addrs & RTA_DST && | |
sin->sin_addr.s_addr == INADDR_ANY && | |
rtm->rtm_addrs & RTA_NETMASK && | |
((ntohl(mask->sin_addr.s_addr) == 0L))) { | |
if_indextoname(rtm->rtm_index, ifname); | |
printf("%s\n",ifname); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment