读取并解析/proc/net/route文件
源码如下
route.h
#ifndef _ROUTE_H
#define _ROUTE_H
struct r_entry {
int dest;
int mask;
int gateway;
char iface[10];
struct r_entry *next;
};
#endif
getrt.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include "route.h"
#define PATH "/proc/net/route"
/*
** open the /proc/net/route file and get the route entry
** return: e r_entry linklist if success, or a NULL pointer if failed
*/
struct r_entry *get_route_entry (void)
{
FILE *fp = NULL;
fp = fopen (PATH, "r");
if (NULL == fp) {
perror ("can't open file!\n");
exit (EXIT_FAILURE);
}
char buf[BUFSIZ] = {'\0'};
int firsttime = 1;
int firstline = 1;
int nouse;
struct r_entry *head, *q, *p;
head = q = p = NULL;
while (!feof (fp)) {
fgets (buf, BUFSIZ, fp);
if (firstline) {
firstline = 0;
continue;
}
p = malloc (sizeof (struct r_entry));
if (NULL == p) {
fprintf (stderr, "can not malloc !");
exit (EXIT_FAILURE);
}
sscanf (buf, "%s%x%x%x%x%x%x%x", p->iface, &p->dest, &p->gateway,
&nouse, &nouse, &nouse, &nouse, &p->mask);
p->next = NULL;
/* add to link */
if (firsttime) {
head = p;
q = p;
firsttime = 0;
}else {
q->next = p;
q = q->next;
}
}
fclose (fp);
return head;
}
int del_route_entry (struct r_entry *head)
{
if (head == NULL)
return 0;
struct r_entry *q, *p;
p = q =head;
for (p = q = head; p != NULL; p = q) {
q = q->next;
free (p);
}
return 0;
}
/*
** display route table
*/
int display_route (void)
{
struct r_entry *head, *p;
char buf1[20] = {'\0'};
char buf2[20] = {'\0'};
char buf3[20] = {'\0'};
head = get_route_entry ();
if (head == NULL) {
fprintf (stderr, "can not get route table\n");
}
printf ("Destination\tGenmask\t\tGateway\t\tUse Iface\n");
struct in_addr gateway;
struct in_addr netmask;
struct in_addr destion;
memset (&gateway, 0, sizeof (struct in_addr));
memset (&netmask, 0, sizeof (struct in_addr));
memset (&destion, 0, sizeof (struct in_addr));
for (p = head; p!= NULL; p = p->next) {
gateway.s_addr = p->gateway;
netmask.s_addr = p->mask;
destion.s_addr = p->dest;
printf ("%s\t%s\t%s\t%s\n",
inet_ntop (AF_INET, &destion, buf1, 20),
inet_ntop (AF_INET, &netmask, buf2, 20),
inet_ntop (AF_INET, &gateway, buf3, 20),
p->iface);
}
del_route_entry (head);
return 0;
}
int main (int argc, char **argv)
{
display_route ();
return 0;
}
测试环境:gcc version 4.7.3 (Ubuntu/Linaro 4.7.3-1ubuntu1)