[转]Detect network cable plugged or unplugged
时间:2010-08-18 来源:zimang
#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");
if (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;
}
当然,这个代码还需要驱动的支持,如果一个完善的驱动,都会去设置IFF_RUNNING和IFF_UP标志。
如果Ifconfig eth0 down, IFF_RUNNING和IFF_UP将被unset,否则IFF_UP将被set。
如果网线拔出,IFF_RUNNING将被unset,插上网线将被set。
http://cblfs.cross-lfs.org/index.php/Netplug
#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");
if (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;
}
当然,这个代码还需要驱动的支持,如果一个完善的驱动,都会去设置IFF_RUNNING和IFF_UP标志。
如果Ifconfig eth0 down, IFF_RUNNING和IFF_UP将被unset,否则IFF_UP将被set。
如果网线拔出,IFF_RUNNING将被unset,插上网线将被set。
http://cblfs.cross-lfs.org/index.php/Netplug
|
相关阅读 更多 +