用ioctl实现打开和关闭网卡
//启动网卡接口
int SetEtherStatusUP(const char *ethNum)
{
struct ifreq ifr;
int sockfd;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("Create socket fails!\n");
return -1;
}
strcpy(ifr.ifr_name, ethNum);
if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0)
{
printf("ioctl SIOCGIFFLAGS fails!\n");
close(sockfd);
return -1;
}
ifr.ifr_flags |= IFF_UP;
if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0)
{
printf("ioctl SIOCSIFFLAGS fails!\n");
close(sockfd);
return -1;
}
close(sockfd);
return 1;
}
//关闭网卡接口
int SetEtherStatusDOWN(const char *ethNum)
{
struct ifreq ifr;
int sockfd;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
printf("Create socket fails!\n");
return -1;
}
strcpy(ifr.ifr_name, ethNum);
if (ioctl(sockfd, SIOCGIFFLAGS, &ifr) < 0)
{
printf("ioctl SIOCGIFFLAGS fails!\n");
close(sockfd);
return -1;
}
ifr.ifr_flags &= ~IFF_UP;
if (ioctl(sockfd, SIOCSIFFLAGS, &ifr) < 0)
{
printf("ioctl SIOCSIFFLAGS fails!\n");
close(sockfd);
return -1;
}
close(sockfd);
return 1;
}