我需要监控网络接口的本地地址(IP),例如当其更改或接口被拔出时执行某些操作,我想知道最佳方法是什么。目前我正在使用InterfaceByName在无限循环中获取和验证/匹配接口详细信息。我要监视多个接口,所以我想知道这是否有问题,或者是否应该使用一些延迟等。如果操作系统能够在接口更新时发送信号那就太好了,但是我不知道有这样的东西。
sysfs
文件。$ cat /sys/class/net/eth0/operstate
up
$ cat /sys/class/net/eth0/carrier
1
NETLINK_ROUTE
更新。有一些 Go netlink packages 可用,但我不确定它们有多通用。package main
import (
"fmt"
"net"
"os"
"syscall"
"time"
)
func main() {
interfaceName := "eth0" // Replace with your interface name
// Retrieve the initial IP address of the interface
initialIP, err := getCurrentIPAddress(interfaceName)
if err != nil {
fmt.Println("Failed to retrieve initial IP address:", err)
os.Exit(1)
}
fmt.Println("Initial IP address:", initialIP)
// Start monitoring the interface
for {
time.Sleep(time.Second) // Delay between each iteration
// Retrieve the current IP address of the interface
currentIP, err := getCurrentIPAddress(interfaceName)
if err != nil {
fmt.Println("Failed to retrieve current IP address:", err)
continue
}
// Compare current IP with initial IP
if currentIP != initialIP {
fmt.Println("IP address changed:", currentIP)
// Perform actions here for IP address change
// Update the initial IP address for subsequent comparisons
initialIP = currentIP
}
}
}
func getCurrentIPAddress(interfaceName string) (string, error) {
iface, err := net.InterfaceByName(interfaceName)
if err != nil {
return "", err
}
addrs, err := iface.Addrs()
if err != nil {
return "", err
}
for _, addr := range addrs {
ipNet, ok := addr.(*net.IPNet)
if ok && !ipNet.IP.IsLoopback() && ipNet.IP.To4() != nil {
return ipNet.IP.String(), nil
}
}
return "", fmt.Errorf("No IPv4 address found for interface")
}