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.

      int system(const char *command);

      system() executes a command specified in command by calling /bin/sh -c command,
      and returns after the command has been completed.

Let us see below code.

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

// make bash command
char *command = "cat /sys/class/net/eth0/carrier";

int main() {

	system(command);
	return 0;
}

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.
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

// make bash command
char *command = "cat /sys/class/net/eth0/carrier > /tmp/xyz.txt";

int main() {

	system(command);
	// open file to read
	freopen("/tmp/xyz.txt", "r", stdin);
	int status = -1;
	scanf("%d", &status);

	if (status == 0)
		printf("The cable is not plugged\n");
	else
		printf("The cable is plugged\n");
	return 0;
}

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

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>

// make bash command
char *command = "cat /sys/class/net/eth0/carrier";

int main() {

	FILE *p;
	p = popen(command, "r");

	if (!p) {
		fprintf(stderr, "Error opening pipe.\n");
		return 1;
	}
	char str[80];
	while (!feof(p)) {
		sprintf(str, "%c", fgetc(p));
		if (str[0] == '0')
			printf("Cable is not plugged\n");
		else
			printf("Cable is plugged/connected\n");
		break;
	}

	if (pclose(p) == -1) {
		fprintf(stderr, " Error!\n");
		return 1;
	}

	return 0;
}

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