[英]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.我正在尝试读取特定接口以及该接口中的所有虚拟 IP。
Here is and example of the linux ifconfig -a | grep -A eth0
这是 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)
I tried like this in go code:我在 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: 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?如何读取 eth0:2 的 IP 地址?
Thanks James谢谢詹姆斯
Call Interface.Addrs()
to get the interface's addresses, and type-assert *net.IPNet
from the addresses.调用
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. 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.