Linux下虚拟网卡tun/tap

#include <stdio.h>
#include <string.h>
#include <linux/if_tun.h>
#include <sys/types.h>
#include <net/if.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>

int tun_create(char *dev, int flags)
{
struct ifreq ifr;
int fd;
int cmd;

if ((fd = open("/dev/net/tun", O_RDWR)) < 0)
{
return fd;
}

memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, dev);
ifr.ifr_flags |= flags;

ioctl(fd, TUNSETIFF, (void *)&ifr);
return(fd);
}

int main(int argc, char *argv[])
{
int tun, ret;
unsigned char buf[4096];
unsigned char ip[4];
unsigned char ihl;

tun = tun_create("tun0", IFF_TUN | IFF_NO_PI);
if (tun < 0)
{
perror("tun_create");
return 1;
}
printf("TUN name is %s\n", "tun0");

while (1)
{

ret = read(tun, buf, sizeof(buf));
if (ret < 0)
{
break;
}
ihl = buf[0] & 0xf;
printf("The length of ip header is %d\n", ihl);
memcpy(ip, &buf[12], 4);
memcpy(&buf[12], &buf[16], 4);
memcpy(&buf[16], ip, 4);
buf[20] = 0;
*((unsigned short*)&buf[22]) += 8;
printf("read %d bytes\n", ret);
ret = write(tun, buf, ret);
printf("write %d bytes\n", ret);
}

return 0;
}

这段代码基本是网络上复制的。不过网络上的代码没有把头文件帖全,害得我折腾了一番。没啥特别可说的,但有一点不明白的是,见红色部分。IP头的大小正好是20个字节,代码居然在21和23字节做操作,原则上这是option字段。把红色代码注释掉以后,程序可以正常运行,但是时延增加了0.3ms左右。没明白!

posted @ 2016-05-12 16:35  CalvinWang  阅读(1737)  评论(0编辑  收藏  举报