判断接口是否已经打开并运行
来源:互联网 发布:程序员术语 编辑:程序博客网 时间:2024/05/03 02:18
#include <stdio.h>#include <string.h>#include <stdlib.h>#include <unistd.h>#include <sys/socket.h>#include <sys/ioctl.h>#include <net/if.h>#include <sys/types.h>#define IFNAMSIZ 16static int IsIfUp(char *ifname);int c;int main( int argc, char *argv[]){ char *ifname; int status=0; if ( argc < 3 ) { printf("Please input two arguments and try it again!\n"); return 0; } while (( c = getopt(argc, argv, "i:")) != -1) { switch(c){ case 'i': printf("The interface is %s.\n", optarg); ifname = optarg; break; case '?': printf("Please input two arguments and try it again!\n"); break; } } if( (status = IsIfUp(ifname)) == 0 ) { printf("The eth0 status is Up!\n"); return 0; } else { printf("The eth0 status is down!\n"); return -1; } }int IsIfUp(char *ifname){ struct ifreq ifr; int sock; sock = socket(AF_INET, SOCK_DGRAM, 0); if(sock < 0) { perror("socket: Unable to open\n"); return (-1); } memcpy(&ifr.ifr_name[0] ,ifname,IFNAMSIZ); if(ioctl(sock, SIOCGIFFLAGS, &ifr) < 0 ) { perror("ioctl: SIOCGIFFLAGS"); close(sock); return (-1); } if (!(ifr.ifr_flags & (IFF_UP|IFF_RUNNING))) { close(sock); return (-1); } close(sock); return 0;}