#include <stdio.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <ctype.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <net/if.h> #define BUFFER_SIZE 4096 int getgatewayandiface(in_addr_t * addr, char *interface) { long destination, gateway; char iface[IF_NAMESIZE]; char buf[BUFFER_SIZE]; FILE * file; memset(iface, 0, sizeof(iface)); memset(buf, 0, sizeof(buf)); file = fopen("/proc/net/route", "r"); if (!file) return -1; while (fgets(buf, sizeof(buf), file)) { if (sscanf(buf, "%s %lx %lx", iface, &destination, &gateway) == 3) { if (destination == 0) { /* default */ *addr = gateway; strcpy(interface, iface); fclose(file); return 0; } } } /* default route not found */ if (file) fclose(file); return -1; } int main(int argc, char **argv) { in_addr_t addr = 0; char iface[IF_NAMESIZE]; memset(iface, 0, sizeof(iface)); getgatewayandiface(&addr, iface); printf("%s\n", inet_ntoa(*(struct in_addr *) &addr)); printf("%s\n", iface); return 0; }