简体   繁体   中英

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

I am trying to read a particular interface and all the virtual IP in that interface.

Here is and example of the linux ifconfig -a | grep -A eth0ifconfig -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)

I tried like this in go code:


// 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>

How can I read the IP address of eth0:2?

Thanks James

Call Interface.Addrs() to get the interface's addresses, and type-assert *net.IPNet from the addresses.

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)
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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