#include <unistd.h>
#include <stdio.h>
#include <curses.h>
#include <string.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <signal.h>
#include <unistd.h>
#include <linux/if_tun.h>
#include <netinet/in.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <linux/if.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
//启动网卡接口
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;
}
转载于:https://my.oschina.net/guyson/blog/223383