1

I want to monitor the RUNNING state of a certain network interface in an efficient way, without constantly calling ifconfig every second, or so, and parsing its output. So I'm asking if someone knows a way to efficiently get this state information in Python on Linux.

I know of netifaces, but it doesn't give me interface states. So I don't know if the interface is just available, or really online/running.

Then I looked into psutil, but if I'd not missed something there, it has no access to this kind of network interface state either. If I'm wrong, I will be happy to get corrected and get specific info on how to achieve my goal.

TheDiveO
  • 561
  • 1
  • 6
  • 17
  • You should take a look in `/sys/net//`. `carrier` and `operstate` are places you can start. –  Jul 14 '17 at 21:27
  • @yoonix is there a way to avoid constantly opening, reading, then closing the /sys/net pseudo files? – TheDiveO Jul 14 '17 at 21:32
  • If you want to read updates, no. How else are you going to read the contents? What's the problem with opening reading and closing? This is what the /sys filesystem is for. –  Jul 14 '17 at 21:34
  • I was afraid that this causes much higher load than a dedicated socket call I may have overlooked. – TheDiveO Jul 14 '17 at 21:38
  • 1
    @yoonix repeated open/close isn't necessary, a seek works like a charm, and I get fresh state information on each seek()/read(). – TheDiveO Jul 26 '17 at 18:42

1 Answers1

0

It turns out that reading /sys/class/net/eth0/carrier works quite well and efficiently. In particular, it isn't necessary to constantly run the open()/readline()/close() sequence, as this is much less efficient than to simply open() only once and then repeatedly do seek(0) followed by readline().

This all even works across pulling and hot-plugging the network interface.

A flush() isn't necessary and won't do anything anyway in this case, as the open(...,'r') is read-only and flush() is a no-op in this mode, per the official Python documentation.

TheDiveO
  • 561
  • 1
  • 6
  • 17