blob: 372a73ed078abdd29cee138b470c20f7d9bdc434 [file] [log] [blame]
// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package network
import (
// ipv4Regex is a regex that matches IPv4 address.
var ipv4Regex = regexp.MustCompile(`(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})`)
// Gateway returns IPv4 gateway address of an interface by calling "ip route get".
func Gateway(ctx context.Context, ifname string) (string, error) {
// Get the physical interface gateway address.
out, err := testexec.CommandContext(ctx, "/bin/ip", "route", "get", "", "oif", ifname).Output(testexec.DumpLogOnError)
if err != nil {
return "", errors.Wrapf(err, "failed to get gateway address for interface %s", ifname)
// ip route get returns address of the next hop to with the following format
// via "gateway_address" ...
// e.g. " via ..."
// Gateway is the second valid IPv4 address.
m := ipv4Regex.FindAllString(string(out), 2)
if len(m) < 2 {
return "", errors.Errorf("failed to parse gateway address from 'ip route' for interface %s", ifname)
gateway := m[1]
return gateway, nil