#include#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include //启动网卡接口 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; }}int tun_create(char *dev, int flags){ struct ifreq ifr; int fd, err; if ((fd = open("/dev/net/tun", O_RDWR)) < 0) { return fd; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags |= flags; if (*dev != '\0') strncpy(ifr.ifr_name, dev, IFNAMSIZ); if ((err = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0) { close(fd); return err; } strcpy(dev, ifr.ifr_name); return fd;}int main(){ int tun4; char tun4_name[IFNAMSIZ]="tun4"; //tun4_name[0]='\0'; tun4 = tun_create(tun4_name, IFF_TAP | IFF_NO_PI); //tun4 = tun_create(tun4_name, IFF_TUN | IFF_NO_PI); printf("dev=%s\n",tun4_name); getchar(); SetEtherStatusUP(tun4_name); printf("up\n"); getchar(); SetEtherStatusDOWN(tun4_name); printf("down\n"); return 0;}