8

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?

Jeff Schaller
  • 66,199
  • 35
  • 114
  • 250

2 Answers2

18

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

slm
  • 363,520
  • 117
  • 767
  • 871
5

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

Cristian Ciupitu
  • 2,430
  • 1
  • 22
  • 29