Detect network cable plugged or unplugged

Source: Internet
Author: User
Tags socket error

# Include <stdlib. h>
# Include <stdio. h>
# Include
<String. h>
# Include <unistd. h>
# Include
<Sys/IOCTL. h>
# Include <net/If. h>
# Include
<ARPA/inet. h>

Int main (INT argc, char ** argv)

Int fd_recv =-1;
Struct ifreq IFR;

Fd_recv =
Socket (af_inet, sock_packet, htons (0x0003 ));
If (fd_recv <0 ){

Fprintf (stderr, "PACKET socket error/N ");
Exit (-1 );


Strcpy (IFR. ifr_name, "eth0 ");
(IOCTL (fd_recv, siocgifflags, & IFR) <0 ){

Fprintf (stderr, "IOCTL siocgifflags error/N ");
Else {

/* Network cable plug-in, iff_running set, else not */

Fprintf (stderr, "iff_running-> % d/N", IFR. ifr_flags &
Iff_running? 1: 0 );

/* Ifconfig eth0 up, iff_up
Set, else not */
Fprintf (stderr, "iff_up-> % d/N ",
IFR. ifr_flags & iff_up? 1: 0 );

Close (fd_recv );
Return 0;

Of course, this Code also requires driver support, if
The iff_running and iff_up flag will be set for a complete driver.

If ifconfig eth0 down,
Iff_running and iff_up will be unset; otherwise, iff_up will be set.
If the network cable is disconnected, iff_running will be unset and plugged in
The network will be set.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.