본것중에 가장 간단하게 /proc/net/route를 파싱하는 소스인 듯하다.
아무튼 route로 출력하는 default가 UG 플래그로 default gateway이며,
파일에서는 Destination과 Mask가 0x00000000 인 녀석이 default gateway이다.
[링크 : http://elenoa.tistory.com/72]
# 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이다.
01 | #include "stdio.h" |
02 | #include "stdlib.h" |
03 | #include "unistd.h" |
04 |
05 | #define IP_PRINT(a) \ |
06 | *((unsigned char *)(&a)), \ |
07 | *(((unsigned char *)(&a)) + 1), \ |
08 | *(((unsigned char *)(&a)) + 2), \ |
09 | *(((unsigned char *)(&a)) + 3) |
10 |
11 | int main() |
12 | { |
13 | FILE * fp = fopen ( "/proc/net/route" , "r" ); |
14 | char buf[256]; |
15 | static char iface[256]; |
16 | unsigned int destination, gateway, flags, refcnt, use, metric, mask; |
17 | int ret; |
18 |
19 | if (fp == NULL) |
20 | exit (-1); |
21 |
22 | while ( fgets (buf, 255, fp)) { |
23 | if (! strncmp (buf, "Iface" , 5)) |
24 | continue ; |
25 |
26 | ret = sscanf (buf, "%s\t%x\t%x\t%d\t%d\t%d\t%d\t%x" , |
27 | iface, &destination, &gateway, &flags, |
28 | &refcnt, &use, &metric, &mask); |
29 |
30 | if (ret < 8) { |
31 | fprintf (stderr, "ERROR: line read error\n" ); |
32 | continue ; |
33 | } |
34 |
35 | if (destination != 0) { |
36 | fprintf (stderr, "%s: gateway %u.%u.%u.%u, " |
37 | "destination %u.%u.%u.%u netmask %u.%u.%u.%u\n" , |
38 | iface, |
39 | IP_PRINT(gateway), |
40 | IP_PRINT(destination), |
41 | IP_PRINT(mask)); |
42 | continue ; |
43 | } |
44 |
45 | if (mask != 0) { |
46 | fprintf (stderr, "%s: gateway %u.%u.%u.%u, default, " |
47 | "but have netmask %u.%u.%u.%u???\n" , |
48 | iface, |
49 | IP_PRINT(gateway), |
50 | IP_PRINT(mask)); |
51 | continue ; |
52 | } |
53 |
54 | fprintf (stderr, "%s: gateway %u.%u.%u.%u, default\n" , |
55 | iface, |
56 | IP_PRINT(gateway)); |
57 | } |
58 | fclose (fp); |
59 | } |
[링크 : http://elenoa.tistory.com/72]
'Linux' 카테고리의 다른 글
lsof - list Open File (0) | 2009.12.07 |
---|---|
filesystem - msdos, vfat, umsdos (0) | 2009.12.06 |
좀비 프로세스 생성하기(!) (0) | 2009.11.20 |
ps에서 [프로세스] 의 의미 - bracket process name in ps (0) | 2009.11.20 |
ps - Process Status (2) | 2009.11.20 |