How do i get the default gateway in LINUX given the destination?

前端 未结 15 2136
清酒与你
清酒与你 2020-12-13 07:02

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 return

15条回答
  •  遥遥无期
    2020-12-13 07:35

    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/ {print $3}'
    

    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/ {print \$3; found=1} END{exit !found}"
    

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

提交回复
热议问题