#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 16
static 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;
}
判斷接口是否已經打開並運行
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.