먼저 제타위키의 글을 참조하시기 바랍니다.
이 글을 작성한 이유는 커널 버전에 따라서 위 글에 소개된 모든 방법이 유용하지는 않는 것을 발견해서입니다.
간단하게 기록용으로 남기자면 ip route 명령으로 커널 버전 상관없이 확실하게 게이트웨이 주소를 얻을 수 있습니다.
[sr@localhost ~]$ ip route
default via 11.11.11.129 dev enp2s0 proto static metric 100
default via 192.168.0.1 dev enp3s5 proto static metric 101
192.168.0.0/24 dev enp3s5 proto kernel scope link src 192.168.0.3 metric 100
11.11.11.128/25 dev enp2s0 proto kernel scope link src 11.11.11.222 metric 100
위 예제를 보면 default via IP 형태의 문자열이 보이는데 이 IP 가 게이트웨이 주소입니다.
ip route | grep default | awk '{print $3}' 명령을 사용하면 해당 IP 만 추출할 수 있습니다.
다만, 위와 같이 네트워크 장치가 여러개라면 문자열에서 ip 대역을 검사해서 구별해줘야겠죠?
그 외의 명령은 3.x 대 이상의 커널에서는 원하는 값을 바로 얻지 못하는 것처럼 보입니다.
[sr@localhost ~]$ route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default gateway 0.0.0.0 UG 100 0 0 enp2s0
default gateway 0.0.0.0 UG 101 0 0 enp3s5
192.168.0.0 0.0.0.0 255.255.255.0 U 100 0 0 enp3s5
11.11.11.128 0.0.0.0 255.255.255.128 U 100 0 0 enp2s0
[sr@localhost ~]$ netstat -r
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
default gateway 0.0.0.0 UG 0 0 0 enp2s0
default gateway 0.0.0.0 UG 0 0 0 enp3s5
192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 enp3s5
11.11.11.128 0.0.0.0 255.255.255.128 U 0 0 0 enp2s0
[sr@localhost ~]$ uname -a
Linux localhost.localdomain 3.10.0-229.el7.x86_64 #1 SMP Fri Mar 6 11:36:42 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
2.x 대 커널에서는 위 글에 언급된 내용대로 동작하는 것을 확인할 수 있습니다.
[root@SHost ~]# route
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
169.254.0.0 * 255.255.0.0 U 0 0 0 eth0
default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
[root@SHost ~]# netstat -r
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
192.168.0.0 * 255.255.255.0 U 0 0 0 eth0
169.254.0.0 * 255.255.0.0 U 0 0 0 eth0
default 192.168.0.1 0.0.0.0 UG 0 0 0 eth0
[root@SHost ~]# uname -a
Linux SHost 2.6.15-smp #7 SMP Tue Oct 23 11:26:28 KST 2007 i686 i686 i386 GNU/Linux
그래서 만약 시스템 도구를 통해서 게이트웨이 주소를 얻어오는 기능을 사용한다면 ip route 명령을 사용하길 추천합니다.