直接贴代码:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
int check_nic(char *nic_name)
{
struct ifreq ifr;
int skfd = socket(AF_INET, SOCK_DGRAM, 0);
strcpy(ifr.ifr_name, nic_name);
if (ioctl(skfd, SIOCGIFFLAGS, &ifr) < 0)
{
close(skfd);
return -1;
}
if(ifr.ifr_flags & IFF_RUNNING)
{
close(skfd);
return 0;
}
else
{
close(skfd);
return -1;
}
}
int main(int argc, char const *argv[])
{
while(1)
{
printf("link status :%d\n",check_nic("eth0"));
sleep(1);
}
return 0;
}