Skip to content

Instantly share code, notes, and snippets.

@aerok
Last active February 17, 2016 10:34
Show Gist options
  • Save aerok/807c8299557e7bbf0a0c to your computer and use it in GitHub Desktop.
Save aerok/807c8299557e7bbf0a0c to your computer and use it in GitHub Desktop.
findroute
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define VERSION "0.1"
#define PATH "/proc/net/route"
static int find_route (struct in_addr ia)
{
struct
{
char iface[10];
int dest;
int gateway;
int mask;
} route;
struct in_addr gateway;
struct in_addr netmask;
struct in_addr destion;
int is_firstline = 1;
int is_default = 1;
char buf[BUFSIZ] = { '\0' };
FILE *fp = NULL;
fp = fopen (PATH, "r");
if (NULL == fp)
{
perror ("cannot open route table!\n");
return -1;
}
while (fgets (buf, BUFSIZ, fp) != NULL)
{
if (is_firstline)
{
is_firstline = 0;
continue;
}
sscanf (buf, "%s%x%x%*x%*x%*x%*x%x%*x%*x%*x", route.iface, &route.dest, &route.gateway, &route.mask);
destion.s_addr = route.dest;
gateway.s_addr = route.gateway;
netmask.s_addr = route.mask;
if (ia.s_addr == route.dest)
{
printf ("via the gateway: %s\n", inet_ntoa (gateway));
is_default = 0;
break;
}
}
if (is_default)
{
printf ("via default gateway: %s\n", inet_ntoa (gateway));
}
fclose (fp);
return 0;
}
int main (int argc, char **argv)
{
struct in_addr ia;
int opt;
while ((opt = getopt (argc, argv, "ha:")) != -1)
{
switch (opt)
{
case 'a':
if (inet_aton (optarg, &ia))
{
return find_route (ia) ? EXIT_SUCCESS : EXIT_FAILURE;
}
else
{
puts ("invalid address");
return EXIT_FAILURE;
}
default:
printf ("version %s\n" "usage: %s [-h help] [-a address]\n", VERSION, argv[0]);
return (opt == '?' || opt == 'h') ? EXIT_SUCCESS : EXIT_FAILURE;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment