1 Star 0 Fork 1

laoyening/nice_tcp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
main.c 1.47 KB
一键复制 编辑 原始数据 按行查看 历史
laoyening 提交于 2020-06-16 21:44 . 测试虚拟网卡
#include <net/if.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <linux/if_tun.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static int tun_fd;
static char* dev;
#define CLEAR(x) memset(&(x), 0, sizeof(x))
static int tun_alloc(char *dev)
{
struct ifreq ifr;
int fd, err;
if( (fd = open("/dev/net/tun", O_RDWR)) < 0 ) {
perror("Cannot open TUN/TAP dev\n"
"Make sure one exists with "
"'$ mknod /dev/net/tap c 10 200'");
exit(1);
}
CLEAR(ifr);
/* Flags: IFF_TUN - TUN device (no Ethernet headers)
* IFF_TAP - TAP device
*
* IFF_NO_PI - Do not provide packet information
*/
ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
if( *dev ) {
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
}
if( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) < 0 ){
perror("ERR: Could not ioctl tun");
close(fd);
return err;
}
strcpy(dev, ifr.ifr_name);
return fd;
}
int main()
{
int nread;
char buffer[1500];
dev = calloc(10, 1);
tun_fd = tun_alloc(dev);
if(tun_fd < 0){
printf("error!!");
exit(1);
}
while(1){
nread = read(tun_fd,buffer,sizeof(buffer));
if(nread < 0){
printf("error!!");
exit(1);
}
printf("Read %d bytes from tun/tap device\n",nread);
}
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/yeyening/nice_tcp.git
git@gitee.com:yeyening/nice_tcp.git
yeyening
nice_tcp
nice_tcp
master

搜索帮助