liuxiaolong
2022-06-28 37714b1093c04061e636e5b1d27179652e671c0a
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package sockaddr
 
import (
    "errors"
    "os/exec"
)
 
type routeInfo struct {
    cmds map[string][]string
}
 
// NewRouteInfo returns a Linux-specific implementation of the RouteInfo
// interface.
func NewRouteInfo() (routeInfo, error) {
    // CoreOS Container Linux moved ip to /usr/bin/ip, so look it up on
    // $PATH and fallback to /sbin/ip on error.
    path, _ := exec.LookPath("ip")
    if path == "" {
        path = "/sbin/ip"
    }
 
    return routeInfo{
        cmds: map[string][]string{"ip": {path, "route"}},
    }, nil
}
 
// GetDefaultInterfaceName returns the interface name attached to the default
// route on the default interface.
func (ri routeInfo) GetDefaultInterfaceName() (string, error) {
    out, err := exec.Command(ri.cmds["ip"][0], ri.cmds["ip"][1:]...).Output()
    if err != nil {
        return "", err
    }
 
    var ifName string
    if ifName, err = parseDefaultIfNameFromIPCmd(string(out)); err != nil {
        return "", errors.New("No default interface found")
    }
    return ifName, nil
}