본것중에 가장 간단하게 /proc/net/route를 파싱하는 소스인 듯하다.
# cat /proc/net/route
Iface Destination Gateway Flags RefCnt Use Metric Mask MTU Window IRTT
eth0 000AA8C0 00000000 0001 0 0 0 00FFFFFF 0 0 0
eth0 00000000 010AA8C0 0003 0 0 0 00000000 0 0 0
# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.10.0 * 255.255.255.0 U 0 0 0 eth0
default 192.168.10.1 0.0.0.0 UG 0 0 0 eth0
|
아무튼 route로 출력하는 default가 UG 플래그로 default gateway이며,
파일에서는 Destination과 Mask가 0x00000000 인 녀석이 default gateway이다.
#include "stdio.h"
#include "stdlib.h"
#include "unistd.h"
#define IP_PRINT(a) \
*((unsigned char *)(&a)), \
*(((unsigned char *)(&a)) + 1), \
*(((unsigned char *)(&a)) + 2), \
*(((unsigned char *)(&a)) + 3)
int main()
{
FILE* fp = fopen("/proc/net/route", "r");
char buf[256];
static char iface[256];
unsigned int destination, gateway, flags, refcnt, use, metric, mask;
int ret;
if (fp == NULL)
exit(-1);
while (fgets(buf, 255, fp)) {
if (!strncmp(buf, "Iface", 5))
continue;
ret = sscanf(buf, "%s\t%x\t%x\t%d\t%d\t%d\t%d\t%x",
iface, &destination, &gateway, &flags,
&refcnt, &use, &metric, &mask);
if (ret < 8) {
fprintf(stderr, "ERROR: line read error\n");
continue;
}
if (destination != 0) {
fprintf(stderr, "%s: gateway %u.%u.%u.%u, "
"destination %u.%u.%u.%u netmask %u.%u.%u.%u\n",
iface,
IP_PRINT(gateway),
IP_PRINT(destination),
IP_PRINT(mask));
continue;
}
if (mask != 0) {
fprintf(stderr, "%s: gateway %u.%u.%u.%u, default, "
"but have netmask %u.%u.%u.%u???\n",
iface,
IP_PRINT(gateway),
IP_PRINT(mask));
continue;
}
fprintf(stderr, "%s: gateway %u.%u.%u.%u, default\n",
iface,
IP_PRINT(gateway));
}
fclose(fp);
}
[링크 :
http://elenoa.tistory.com/72]