Linux узнать default gateway

How do I get the default gateway in Linux given the destination?

I’m trying to get the default gateway, using the destination 0.0.0.0 . I used the command netstat -rn | grep 0.0.0.0 and it returned this list:

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

My goal here is to ping the default gateway using the destination 0.0.0.0 , which is 133.88.31.70 , but this one returns a list because of using grep . How do I get the default gateway only? I need it for my Bash script to determine whether the network connection is up or not.

15 Answers 15

You can get the default gateway using ip command like this:

IP=$(/sbin/ip route | awk '/default/ < print $3 >') echo $IP 

What if there is more than one default gateway? Your script yields me 192.168.1.1 192.168.0.1 , and this is true: I have two gateways to internet. But the main one is 192.168.1.1 . Should the first default value be selected as the main (prioritary) one?

@SopalajodeArrierez In my opinion, you should select the gateway for the particular interface you’re interested in, e.g. /sbin/ip route |grep ‘^default’ | awk ‘/eth1/ ‘ when you want to know the gateway for eth1 .

@KyleStrand There is a «metric» value for each route entry. The smaller one gets priority. Is there any way to use that value to find the default gateway?

@StarBrilliant There might be some way to do that with ‘awk’, but failing that I’d recommend just writing a small script that parses each line of output and searches for the smallest metric value.

@StarBrilliant Actually, if you know what column the «metric» will be in, sort will do most of the work. -k3,3 specifies (for instance) sorting by the third column, and -n indicates that the sort should be done numerically. You can then use head -1 to get only the first line, and get the relevant column (the gateway) using awk as in the answer.

The ip route command from the iproute2 package can select routes without needing to use awk / grep , etc to do the selection.

To select the default route (from possibly many):

$ ip -4 route show default # use -6 instead of -4 for ipv6 selection. default via 172.28.206.254 dev wlp0s20f3 proto dhcp metric 600 

To select the next hop for a particular interface:

$ ip -4 route list type unicast dev eth0 exact 0/0 # Exact specificity default via 172.29.19.1 dev eth0 

In case of multiple default gateways, you can select which one gets chosen as the next hop to a particular destination address:

$ ip route get $(dig +short google.com | tail -1) 173.194.34.134 via 172.28.206.254 dev wlan0 src 172.28.206.66 cache 

You can then extract the value using sed / awk / grep , etc. Here is one example using bash ‘s read builtin:

Читайте также:  Ubuntu install util linux

I like this because ip already outputs the correct line. A slightly improved version based on this is: ip -4 route list 0/0 | cut -d ‘ ‘ -f 3

@tosh — technically, they are the same 0.0.0.0/0.0.0.0 is the default route — as for the example ip route show to default or perhaps ip route show default would be more explicit, I will update.

Why do these linux tools rarely provide a way to output just the information you want instead of having to awk sed grep cut? Why is there not just a simple -o/—output via flag to route so you do not have to worry about the output format changing.

route -n|grep "UG"|grep -v "UGH"|cut -f 10 -d " " 

route -n | awk ‘$4 == «UG» ‘ for something using the same idea but less hacky

This simple perl script will do it for you.

#!/usr/bin/perl $ns = `netstat -nr`; $ns =~ m/0.0.0.0\s+(8+.4+.4+.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:

or if you need it inside a bash expression:

I know this is years old. the problem with your regex is it will match anything that has 0.0.0.0 followed by an ip address. this means if your gateway is 0.0.0.0 then it will return the genmask. Specifically, the «G» flag indicates a gateway. something like this would be more accurate: echo $(route -n | perl -ne ‘print m/0.0.0.0\s+(2+.1+.9+.4+)\s+0.0.0.0\s+\wG/g’) there is no difference between netstat -nr and route -n

#!/bin/sh GATEWAY_DEFAULT=$(ip route list | sed -n -e "s/^default.*[[:space:]]\([[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\.[[:digit:]]\+\).*/\1/p") echo $

For a list of all default gateways, use mezgani’s answer, duplicated (and slightly simplified) here:

/sbin/ip route | awk '/^default/ < print $3 >' 

If you have multiple network interfaces configured simultaneously, this will print multiple gateways. If you want to select a single known network interface by name (e.g. eth1 ), simply search for that in addition to filtering for the ^default lines:

/sbin/ip route |grep '^default' | awk '/eth1/ ' 

You can make a script that takes a single network-interface name as an argument and prints the associated gateway:

#!/bin/bash if [[ $# -ne 1 ]]; then echo "ERROR: must specify network interface name!" >&2 exit 1 fi # The third argument of the 'default' line associated with the specified # network interface is the Gateway. # By default, awk does not set the exit-code to a nonzero status if a # specified search string is not found, so we must do so manually. /sbin/ip route | grep '^default' | awk "/$1/ END" 

As noted in the comments, this has the advantage of setting a sensible exit-code, which may be useful in a broader programmatic context.

Читайте также:  Vpn client linux remote

Источник

Как найти IP шлюза по умолчанию в Linux

Favorite

Добавить в избранное

Главное меню » Операционная система Linux » Как найти IP шлюза по умолчанию в Linux

Как найти IP шлюза по умолчанию в Linux

Э тот быстрый совет по Linux показывает вам различные методы для определения IP-адреса шлюза вашего маршрутизатора в командной строке Linux.

В предыдущей статье мы рассказывали вам о поиске IP-адреса в командной строке Linux. В этом кратком совете мы покажем вам, как найти IP-адрес шлюза по умолчанию в командной строке Linux.

Шлюз работает как вход или дверь между двумя сетями. Маршрутизатор является примером шлюза. Весь ваш трафик идет к маршрутизатору, а затем к остальной части Интернета.

Иногда вам нужно знать IP-адрес вашего маршрутизатора. IP-адрес шлюза — это IP-адрес вашего маршрутизатора при обычной настройке.

Мы собираемся использовать команду IP, чтобы показать IP шлюза в Linux.

Откройте терминал и используйте следующую команду:

Вы должны увидеть результат вроде этого:

default via 192.168.0.1 dev wlp58s0 proto dhcp metric 600
169.254.0.0/16 dev wlp58s0 scope link metric 1000
192.168.0.0/24 dev wlp58s0 proto kernel scope link src 192.168.0.106 metric 600

Сосредоточьтесь на строке, которая начинается с default. Это даст IP-адрес шлюза по умолчанию.

В качестве альтернативы и удобства вы можете использовать вышеуказанную команду в сочетании с командой grep:

Это просто даст IP-адрес шлюза по умолчанию в выходных данных:

И, как вы можете видеть, 192.168.0.1 является IP-адресом шлюза по умолчанию в нашем случае.

Другие способы найти IP-адрес шлюза в Linux

Команда IP в Linux обеспечивает большинство ваших основных сетевых потребностей. Но, как вы уже заметили, в Linux существует несколько способов сделать определенные вещи.

Чтобы узнать IP шлюза, вы также можете использовать другие сетевые инструменты командной строки. Позвольте нам показать их вам.

Найти шлюз в Linux с помощью команды route

Вы можете использовать опцию -n с командой route для отображения таблицы маршрутизации с IP-адресами.

Пример вывода должен быть таким:

Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 192.168.0.1 0.0.0.0 UG 600 0 0 wlp58s0 169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 wlp58s0 192.168.0.0 0.0.0.0 255.255.255.0 U 600 0 0 wlp58s0

Обратите внимание на флаги U и G? U означает, что маршрут «вверх», а G означает, что это шлюз.

Показать шлюз в Linux с помощью команды netstat

Чтобы отобразить информацию о шлюзе, вы можете использовать команду netstat и отобразить таблицу маршрутизации, которая также составляет шлюз.

Вывод должен быть идентичен тому, что вы видели с командой route:

Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface 0.0.0.0 192.168.0.1 0.0.0.0 UG 0 0 0 wlp58s0 169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 wlp58s0 192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 wlp58s0

Вы можете идентифицировать шлюз с флагом G.

Заключение

Мы надеемся, что этот быстрый совет по Linux помог вам найти IP-адрес шлюза по умолчанию в командной строке Linux. Добавьте этот веб-сайт в ваш ридер для таких регулярных советов и руководств по Linux.

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Источник

Читайте также:  Linux set owner permission

How to Find Default Gateway IP in Linux

This quick Linux tip shows various methods to find gateway IP address of your router in Linux command line.

In an earlier article, I told you about finding IP address in Linux command line. In this quick tip, I’ll show you how to find the default gateway IP in Linux command line.

A gateway is works as the entrance or a door between two networks. A router is an example of the gateway. All your traffic goes to the router and then to the rest of the internet.

Sometimes, you’ll need to know the IP address of your router. The gateway IP is your router’s IP address in the normal setup.

I am going to use the IP command to show the gateway IP in Linux.

Open a terminal and use the following command:

You should see an output like this:

default via 192.168.0.1 dev wlp58s0 proto dhcp metric 600 169.254.0.0/16 dev wlp58s0 scope link metric 1000 192.168.0.0/24 dev wlp58s0 proto kernel scope link src 192.168.0.106 metric 600

Focus on the line that starts with default. This will give the default gateway IP.

Alternatively and conveniently, you can use the above command in combination with the grep command:

This will just give the default gateway IP in the output:

default via 192.168.0.1 dev wlp1s0 proto dhcp metric 600

And as you can see, 192.168.0.1 is the default gateway IP in my case.

Other methods to find gateway IP address in Linux

The IP command in Linux provides most of your basic networking needs. But as you have already noticed by now, there are multiple ways to do a certain things in Linux.

To know the gateway IP, you can use other networking command line tools as well. Let me show them to you.

Find gateway in Linux with route command

You can use the -n option with the route command to display the routing table with the IP addresses.

The sample output should be like this:

Kernel IP routing table Destination Gateway Genmask Flags Metric Ref Use Iface 0.0.0.0 192.168.0.1 0.0.0.0 UG 600 0 0 wlp58s0 169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 wlp58s0 192.168.0.0 0.0.0.0 255.255.255.0 U 600 0 0 wlp58s0

Notice the U and G flags? U means the route is ‘up’ and the G indicates that it is gateway.

Show gateway in Linux with netstat command

To display the gateway information, you can use the netstat command and display the routing table that consists the gateway as well.

Output should be identical to what you saw with the route command:

Kernel IP routing table Destination Gateway Genmask Flags MSS Window irtt Iface 0.0.0.0 192.168.0.1 0.0.0.0 UG 0 0 0 wlp58s0 169.254.0.0 0.0.0.0 255.255.0.0 U 0 0 0 wlp58s0 192.168.0.0 0.0.0.0 255.255.255.0 U 0 0 0 wlp58s0

You can identify the gateway with the G flag.

I hope this quick Linux tip helped you in finding the default gateway IP in Linux command line. Add this website to your feed reader for such regular Linux tips and tutorials.

Источник

Оцените статью
Adblock
detector