How do i get the default gateway in LINUX given th

2019-03-08 10:11发布

I'm trying to get the default gateway, using the destination 0.0.0.0

I used this command: netstat -rn | grep 0.0.0.0

And it returned this list:

**Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface<br>
10.9.9.17       0.0.0.0         255.255.255.255 UH        0 0          0 tun0<br>
133.88.0.0      0.0.0.0         255.255.0.0     U         0 0          0 eth0<br>
0.0.0.0         133.88.31.70    0.0.0.0         UG        0 0          0 eth0**<br>

My goal here is to ping the default gateway using destination 0.0.0.0; thus, that is 133.88.31.70; but this one returns a list because of using grep.

How do i get the default gateway only? I will need it for my bash script to identify if net connection is up or not.

标签: shell gateway
14条回答
聊天终结者
2楼-- · 2019-03-08 10:53

use command below:

route -n | grep '^0\.0\.\0\.0[ \t]\+[1-9][0-9]*\.[1-9][0-9]*\.[1-9][0-9]*\.[1-9][0-9]*[ \t]\+0\.0\.0\.0[ \t]\+[^ \t]*G[^ \t]*[ \t]' | awk '{print $2}'
查看更多
祖国的老花朵
3楼-- · 2019-03-08 10:55

If you know that 0.0.0.0 is your expected output, and will be at the beginning of the line, you could use the following in your script:

IP=`netstat -rn | grep -e '^0\.0\.0\.0' | cut -d' ' -f2`

then reference the variable ${IP}.

It would be better to use awk instead of cut here... i.e.:

IP=`netstat -rn | grep -e '^0\.0\.0\.0' | awk '{print $2}'`
查看更多
成全新的幸福
4楼-- · 2019-03-08 11:00

works on any linux:

route -n|grep "UG"|grep -v "UGH"|cut -f 10 -d " "
查看更多
SAY GOODBYE
5楼-- · 2019-03-08 11:03

The following command returns the default route gateway IP on a Linux host using only bash and awk:

printf "%d.%d.%d.%d" $(awk '$2 == 00000000 && $7 == 00000000 { for (i = 8; i >= 2; i=i-2) { print "0x" substr($3, i-1, 2) } }' /proc/net/route)

This should even work if you have more than one default gateway as long as their metrics are different (and they should be..).

查看更多
叛逆
6楼-- · 2019-03-08 11:04

This simple perl script will do it for you.

#!/usr/bin/perl

$ns = `netstat -nr`;

$ns =~ m/0.0.0.0\s+([0-9]+.[0-9]+.[0-9]+.[0-9]+)/g;

print $1

Basically, we run netstat, save it to $ns. Then find the line that starts off with 0.0.0.0. Then the parentheses in the regex saves everything inside it into $1. After that, simply print it out.

If it was called null-gw.pl, just run it on the command like:

perl null-gw.pl

or if you need it inside a bash expression:

echo $(perl null-gw.pl)

Good luck.

查看更多
女痞
7楼-- · 2019-03-08 11:04

netstat -rn | grep 0.0.0.0 | awk '{print $2}' | grep -v "0.0.0.0"

查看更多
登录 后发表回答