Skip to content

Commit

Permalink
utils_net: get default gateway for specific interface
Browse files Browse the repository at this point in the history
Add optional parameter in order to retrieve the default gateway
for a specific interface.

On a system with two interfaces, the routes might look like

```
default via 10.172.161.254 dev enc1 proto dhcp src 10.172.160.70 metric 100
default via 192.168.126.1 dev enc2 proto dhcp src 192.168.126.48 metric
102
```

Filtering only by default will return two ips

```
10.172.161.254
192.168.126.1
```

The change allows us to select the interface and thus retrieve only

```
192.168.126.1
```

Signed-off-by: Sebastian Mitterle <[email protected]>
  • Loading branch information
smitterl committed Dec 22, 2023
1 parent 7a3f9a6 commit f0d842b
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions virttest/utils_net.py
Original file line number Diff line number Diff line change
Expand Up @@ -3893,14 +3893,15 @@ def get_host_iface():


def get_default_gateway(iface_name=False, session=None, ip_ver='ipv4',
force_dhcp=False):
force_dhcp=False, target_iface=None):
"""
Get the Default Gateway or Interface of host or guest.
:param iface_name: Whether default interface (True), or default gateway
(False) is returned, defaults to False
:param session: shell/console session if any, defaults to None
:param ip_ver: ip version, defaults to 'ipv4'
:param target_iface: if given, get default gateway only for this device
:return: default gateway of target iface
"""
if ip_ver == 'ipv4':
Expand All @@ -3911,10 +3912,14 @@ def get_default_gateway(iface_name=False, session=None, ip_ver='ipv4',
raise ValueError(f'Unrecognized IP version {ip_ver}')
if force_dhcp:
ip_cmd = ip_cmd + '|grep dhcp'
if target_iface:
regex = "default.*%s" % target_iface
else:
regex = "default"
if iface_name:
cmd = "%s | awk '/default/ { print $5 }'" % ip_cmd
cmd = "%s | awk '/%s/ { print $5 }'" % (ip_cmd, regex)
else:
cmd = "%s | awk '/default/ { print $3 }'" % ip_cmd
cmd = "%s | awk '/%s/ { print $3 }'" % (ip_cmd, regex)
try:
_, output = utils_misc.cmd_status_output(cmd, shell=True, session=session)
if session:
Expand Down

0 comments on commit f0d842b

Please sign in to comment.