How to detect the physical connected state of a network cable/connector?

后端 未结 15 1376
隐瞒了意图╮
隐瞒了意图╮ 2020-12-04 04:23

In a Linux environment, I need to detect the physical connected or disconnected state of an RJ45 connector to its socket. Preferably using BASH scripting only.

The

15条回答
  •  南方客
    南方客 (楼主)
    2020-12-04 05:06

    I was using my OpenWRT enhanced device as a repeater (which adds virtual ethernet and wireless lan capabilities) and found that the /sys/class/net/eth0 carrier and opstate values were unreliable. I played around with /sys/class/net/eth0.1 and /sys/class/net/eth0.2 as well with (at least to my finding) no reliable way to detect that something was physically plugged in and talking on any of the ethernet ports. I figured out a bit crude but seemingly reliable way to detect if anything had been plugged in since the last reboot/poweron state at least (which worked exactly as I needed it to in my case).

    ifconfig eth0 | grep -o 'RX packets:[0-9]*' | grep -o '[0-9]*'
    

    You'll get a 0 if nothing has been plugged in and something > 0 if anything has been plugged in (even if it was plugged in and since removed) since the last power on or reboot cycle.

    Hope this helps somebody out at least!

提交回复
热议问题