How to check programmatically if the Ethernet cable is plugged in?

20,731

Solution 1

The 2 methods I've seen used predominately are to use ethtool or to manually parse the contents of /sys.

ethtool

For example if your interface is eth0 you can query it using ethtool and then parse for the line, "Link detected".

Example
$ sudo ethtool eth0
Settings for eth0:
    Supported ports: [ TP ]
    Supported link modes:   10baseT/Half 10baseT/Full 
                            100baseT/Half 100baseT/Full 
    Supports auto-negotiation: Yes
    Advertised link modes:  10baseT/Half 10baseT/Full 
                            100baseT/Half 100baseT/Full 
    Advertised auto-negotiation: Yes
    Speed: 100Mb/s
    Duplex: Full
    Port: Twisted Pair
    PHYAD: 1
    Transceiver: internal
    Auto-negotiation: on
    Supports Wake-on: pumbag
    Wake-on: g
    Current message level: 0x00000001 (1)
    Link detected: yes

Specifically this command:

$ ethtool eth0 | grep "Link"
Link detected: yes

If it were down it would say no.

Using /sys

Again assuming we're interested in eth0, you can manually parse the contents of /sys/class/net/ and then eth0 for your device. There are 2 files under this directory that will tell you the status of whether the link is active or not, carrier and operstate:

When the wire is connected these 2 files will present as follows:

$ cat /sys/class/net/eth0/{carrier,operstate}
1
up

When the wire is disconnected these 2 files will present as follows:

$ cat /sys/class/net/eth0/{carrier,operstate}
0
down

References

Solution 2

Use mii-tool (man page):

# mii-tool em1
em1: negotiated 100baseTx-FD flow-control, link ok

There is also nmcli from NetworkManager:

$ nmcli -f capabilities.carrier-detect,capabilities.speed device show em1
CAPABILITIES.CARRIER-DETECT:            yes
CAPABILITIES.SPEED:                     100 Mb/s

* device can be shorten to d

Share:
20,731

Related videos on Youtube

Jeff Schaller
Author by

Jeff Schaller

Unix Systems administrator http://www.catb.org/esr/faqs/smart-questions.html http://unix.stackexchange.com/help/how-to-ask http://sscce.org/ http://stackoverflow.com/help/mcve

Updated on September 18, 2022

Comments

  • Jeff Schaller
    Jeff Schaller over 1 year

    As you know, in Windows when we plug in the network cable, the network symbol will change to another status.

    How can I know whether the cable is plugged in or not via the command prompt in Linux?

  • Anthony Collins
    Anthony Collins over 9 years
    Better solution, but not all interfaces support MII inquiries.