LINUX 虚拟网卡tun例子

2019-07-13 07:43发布

/**
 *  linux TUN 例子 代码来至
 *  http://hi.baidu.com/zkheartboy/blog/item/e96acf33508e4a40ad4b5f88.html和
 *  http://blog.csdn.net/Z_man/archive/2009/05/26/4216530.aspx
 *  建立一个tun0的虚拟网卡进行通信,程序关闭后将消失。
 *  ping 10.0.0.1
 *  Documentation/networking/tuntap.txt
 *  br_select.c bridge based on select system call.
 *  br_sigio.c  bridge based on async io and SIGIO signal.
 *  http://hi.baidu.com/zkheartboy/blog/item/e96acf33508e4a40ad4b5f88.html
 *  http://blogold.chinaunix.net/u3/114446/showart_2245279.html
 *  http://www.ibm.com/developerworks/cn/linux/l-tuntap/index.html
 */
#include #include #include #include #include #include #include #include #include #include #include #include #include /** * 激活接口 */ int interface_up(char *interface_name) { int s; if((s = socket(PF_INET,SOCK_STREAM,0)) < 0) { printf("Error create socket :%d ", errno); return -1; } struct ifreq ifr; strcpy(ifr.ifr_name,interface_name); short flag; flag = IFF_UP; if(ioctl(s, SIOCGIFFLAGS, &ifr) < 0) { printf("Error up %s :%d ",interface_name, errno); return -1; } ifr.ifr_ifru.ifru_flags |= flag; if(ioctl(s, SIOCSIFFLAGS, &ifr) < 0) { printf("Error up %s :%d ",interface_name, errno); return -1; } return 0; } #if 0 /** * 设置接口ip地址 */ int set_ipaddr(char *interface_name, char *ip) { int s; if((s = socket(PF_INET, SOCK_STREAM, 0)) < 0) { printf("Error up %s :%d ",interface_name, errno); return -1; } struct ifreq ifr; strcpy(ifr.ifr_name, interface_name); struct sockaddr_in addr; bzero(&addr, sizeof(struct sockaddr_in)); addr.sin_family = PF_INET; inet_aton(ip, &addr.sin_addr); memcpy(&ifr.ifr_ifru.ifru_addr, &addr, sizeof(struct sockaddr_in)); if(ioctl(s, SIOCSIFADDR, &ifr) < 0) { printf("Error set %s ip :%d ",interface_name, errno); return -1; } return 0; } #endif /** * 创建接口 */ int tun_create(char *dev, int flags) { struct ifreq ifr; int fd, err; if ((fd = open("/dev/net/tun", O_RDWR)) < 0) { printf("Error :%d ", errno); return -1; } memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags |= flags; if (*dev != '