Results 1 to 6 of 6
I wish to write a C program to detect whether the Ethernet cable is plugged or unplugged. I found out by using a command "nm-tool" in Linux terminal will show ...
- 03-11-2009 #1Just Joined!
- Join Date
- Nov 2008
- Posts
- 25
How to Write a Program in C to detect the Ethernet Cable?
I wish to write a C program to detect whether the Ethernet cable is plugged or unplugged. I found out by using a command "nm-tool" in Linux terminal will show me whether a Ethernet cable is plugged or not. If Ethernet cable is plugged, in the device part of eth0, the Hardware Link of Wired Settings will indicate a "yes" and "no" if no Ethernet cable.
Hence, in my previous code, I use one function called popen to read the state as shown below:
However, now my project wish to not use the NetworkManager (where the "nm-tool" command comes from). And this gives me trouble to detect the Ethernet cable. So is there any other method for me to detect the Ethernet cable in C programming?PHP Code:f1 = popen( "nm-tool | grep Link", "r" );
while ( fgets( cmd_line, sizeof cmd_line, f1 ))
{
printf( "%s", cmd_line );
}
pclose( f1 );
if( strstr( cmd_line, "no" ) == NULL )
{
printf( "LAN cable is plugged\n");
}
Any advice is welcomed and appreciated. Thanks for help.
Christyyim
- 03-12-2009 #2Just Joined!
- Join Date
- Dec 2006
- Posts
- 85
perhaps ifupdown or ifconfig?
- 03-13-2009 #3Just Joined!
- Join Date
- Nov 2008
- Posts
- 25
thanks the_ultimate_samurai.
ifconfig can do the task by using command
if there is a cable, it will show "UP BROADCASTRUNNINGMULTICAT", else there will be nothing.Code:ifconfig eth0|sed -n '/running/I p'
another alternative is to get the content of /sys/class/net/eth0/carrier, "0" means cable is unplugged and "1" means cable is plugged.
- 03-14-2009 #4Linux Newbie
- Join Date
- Sep 2004
- Location
- UK
- Posts
- 160
how about ethtool
eg. ethtool eth0 | grep "Link detected"
should give:
Link detected: yes
or
Link detected: no
- 03-14-2009 #5Linux Newbie
- Join Date
- Sep 2004
- Location
- UK
- Posts
- 160
Also take a look at files under /sys/class/net/
for eth0 subdirectory /sys/class/net/eth0/
(files carrier, dormant, operstate) change depending on link conditions:
Code:if up + cable if up + NO cable if down + cable ============= ========== ================== carrier 1 carrier 0 cat: carrier: Invalid argument dormant 0 dormant 0 cat: dormant: Invalid argument operstate up operstate down operstate down
- 03-14-2009 #6Just Joined!
- Join Date
- Nov 2008
- Posts
- 25
Thanks blinky.
I had tried "ethtool eth0" before, but in my case, I had to use "sudo" for this command, so not suitable for my case.
And checked the file "/sys/class/net/eth0/carrier" so far work for me.
Thanks for your information


Reply With Quote