繁体   English   中英

如何使用 golang/net package 在 linux 中读取虚拟 IP

[英]How to read virtual IP in linux using golang/net package

我正在尝试读取特定接口以及该接口中的所有虚拟 IP。

这是 linux ifconfig -a | grep -A eth0的示例ifconfig -a | grep -A eth0

ifconfig -a | grep -A2 eth0
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 100.180.89.148  netmask 255.255.255.224  broadcast 100.180.89.140
        inct6 fe80::ac16:2dff:fead:a321  prefixlen 64  scopeid 0x20<link>
--
eth0:1: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 100.180.89.150  netmask 255.255.255.255  broadcast 100.180.89.150
        ether cc:16:2d:ad:a3:20  txqueuelen 1000  (Ethernet)
--
eth0:2: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 100.180.89.151  netmask 255.255.255.255  broadcast 100.180.89.151
        ether ac:16:2d:ad:a3:20  txqueuelen 1000  (Ethernet)
--
eth0:3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 100.180.89.152  netmask 255.255.255.255  broadcast 100.180.89.152
        ether ac:16:2d:ad:a3:20  txqueuelen 1000  (Ethernet)

我在 go 代码中尝试过这样的:


// nwkIfName = eth0
func networkInterfaces(nwkIfName string) ([]Interfaces, error) {
    ifaces, err := net.Interfaces()
    if err != nil {
        return nil, fmt.Errorf("failed to get network interfaces: %w", err)
    }

    for _, nwIf := range ifaces {
        fmt.Println(nwIf.Name)
        if nwIf.Name == nwkIfName {
            fmt.Println(nwIf.Addrs())
        }
    }
    return nil, nil
}

Output:

[100.180.89.148/27 100.180.89.150/32 100.180.89.151/32 100.180.89.152/32 fe80::ae16:2dff:fead:a320/64] <nil>

如何读取 eth0:2 的 IP 地址?

谢谢詹姆斯

调用Interface.Addrs()以获取接口的地址,并从地址中键入断言*net.IPNet

Use its IPNet.IP field to get just the IP address (of type net.IP ), and its IP.To4() method if you need an IPv4 address.

for _, nwIf := range ifaces {
    fmt.Println(nwIf.Name)
    if nwIf.Name == nwkIfName {
        fmt.Println(nwIf.Addrs())
        addrs, err := nwIf.Addrs()
        if err != nil {
            return nil, fmt.Errorf(
                "failed to get addresses of interface: %s, err: %w",
                nwIf.Name, err,
            )
        }
        for _, addr := range addrs {
            if ipNet, ok := addr.(*net.IPNet); ok {
                fmt.Println("\tIP:", ipNet.IP)
            } else {
                fmt.Println("\tnot IPNet:", addr)
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM