how to check if Ethernet cable is connected Linux.  write a C program to detect whether the Ethernet cable is plugged or unplugged. Let us first learn how to check if Ethernet cable is connected with Linux bash shell commands.

  • Open Linux Terminal.
  • Run command ‘cat /sys/class/net/eth0/carrier’ from terminal.

  • The output of above command will show either 0 or 1. 0 means the Ethernet cable is not connected. 1 means Ethernet cable is connected.

C program to detect whether the Ethernet cable is plugged or unplugged

By using system api we can run the above commands in c program.

Let us see below code.

When we compile and run the above program we will output 0. 0 output is result of command ‘cat /sys/class/net/eth0/carrier’ which is executed by system call system. If we can read the output of command ‘cat /sys/class/net/eth0/carrier’ in c program we can print whether Ethernet cable is plugged or unplugged. Let us find a way to read output.

  • Redirect the output of command to a file by using  ‘cat /sys/class/net/eth0/carrier > /tmp/xyz.txt’
  • Read the file content and check the output.

Another method read shell command output in c program using popen system call

popen system call

The popen() function opens a process by creating a pipe, forking, and invoking the shell. Since a pipe is by definition unidirectional, the type argument may specify only reading or writing, not both; the resulting stream is correspondingly read-only or write-only. Read more from https://linux.die.net/man/3/popen




Related Contents to follow