可以使用 net 包和 os/exec 包来实现:

package main

import (
    "fmt"
    "os/exec"
    "strings"
)

func main() {
    iface := "10.169.1.1"
    cmd := exec.Command("netstat", "-rn")
    output, err := cmd.Output()
    if err != nil {
        panic(err)
    }
    lines := strings.Split(string(output), "\n")
    for _, line := range lines {
        fields := strings.Fields(line)
        if len(fields) > 2 && fields[0] == iface {
            fmt.Printf("Destination: %s, Gateway: %s\n", fields[1], fields[2])
        }
    }
}

这里使用 netstat -rn 命令获取路由表信息,然后遍历每一行,找到接口为指定 IP 的路由,打印出目标地址和网关地址

golang 打印出接口为 1016911的路由

原文地址: https://www.cveoy.top/t/topic/fhqo 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录