netlink icon indicating copy to clipboard operation
netlink copied to clipboard

cannot convert eth (variable of type netlink.Link) to netlink.LinkOperState

Open niski84 opened this issue 1 year ago • 1 comments

I can't figure out why I'm getting this error using the library. What is it that I'm doing wrong?

ethState, err := netlink.LinkOperState(eth)


import (
	"log"
	"time"

	"github.com/vishvananda/netlink"
)

func main() {
	// Get references to the network interfaces.
	eth, err := netlink.LinkByName("enp7s0f1")
	if err != nil {
		log.Fatal(err)
	}
	wifi, err := netlink.LinkByName("wlp0s20f3")
	if err != nil {
		log.Fatal(err)
	}

	// Loop indefinitely.
	for {
		now := time.Now()
		if now.Hour() >= 2 && now.Hour() < 6 {
			// Between 2am and 6am, disconnect the interfaces.
			log.Println("Disconnecting LAN and WiFi")
			err = netlink.LinkSetDown(eth)
			if err != nil {
				log.Println(err)
			}
			err = netlink.LinkSetDown(wifi)
			if err != nil {
				log.Println(err)
			}
		} else {
			// During other hours, check if the interfaces are disconnected.
			ethState, err := netlink.LinkOperState(eth)
			if err != nil {
				log.Println(err)
			}
			wifiState, err := netlink.LinkOperState(wifi)
			if err != nil {
				log.Println(err)
			}

			if ethState == netlink.OperDown && wifiState == netlink.OperDown {
				// Both interfaces are disconnected, connect them.
				log.Println("Reconnecting LAN and WiFi")
				err = netlink.LinkSetUp(eth)
				if err != nil {
					log.Println(err)
				}
				err = netlink.LinkSetUp(wifi)
				if err != nil {
					log.Println(err)
				}
			}
		}

		// Wait for one minute before checking again.
		time.Sleep(time.Minute)
	}
}

niski84 avatar Mar 05 '23 02:03 niski84

A quick check with the sources confirms my limited knowledge in that LinkOperState is a data type, but not a method on Link. It's an attribute of the value returned by Link.Attr(). So IMHO you would need to access it by probably first updating the link information and then getting the OperStatefield:

eth, err := netlink.LinkByIndex(eth.Attr().Index)
ethState := eth.Attr().OperState

thediveo avatar Apr 25 '23 12:04 thediveo