Tun/tap 上网及编程

使用了linux下的虚拟网卡;虚拟网卡Tun/tap驱动是一个开源项目,支持很多的类UNIX平台,OpenVPN和Vtun都是基于它实现隧道包封装。
首先,ubuntu下:

apt-get install uml-utilities--网卡
apt-get install bridge-utils--网桥
virtualBox上网方式有三种
1:nat
这种方式在客户机上不用做设置,直接自动捕获就行了,得到的地址也和外部地址不一样.
我这里是
IP:10.0.2.15
gw:10.0.2.2
可以访问外网,但主客机不能互访。
2:Host Interface
我的方法是:host(ubuntu)创建一虚拟网卡,在virtualbox中的网络部分选择host interface,同时指定该host interface为创建的虚拟网卡;指定为eth0或者不指定的话,会提示failed;
创建一张tap0
#sudo tunctl -t tap0 -u myusername
#sudo ifconfig tap0 up
#sudo ifconfig tap0 192.168.0.1(可以为其他,只要不和host的eth0同一网段)
guest(redhat)启动后,设定eth0与tap0同一网段;
#sudo ifconfig eth0 192.168.0.3
guest和host可以互相通信;
使得guest访问外网,只需将host当成一路由;
对于host,开启转发功能:
#echo 1 > /proc/sys/net/ipv4/ip_forward
对于guest,添加路由表项:
#sudo route add -net 162.*.*.0/* netmask 255.255.255.0 dev eth0
ok
-------------------------------------------
leemars更出了其他四种方案:
-----------------------------------------------------------------------------
方案一:
其实是利用iptables的nat功能来实现主客机通信的
引用自leemars,这个我没试
Host :
#echo 1 > /proc/sys/net/ipv4/ip_forward #打开转发功能
#iptables -t nat -A POSTROUTING -j MASQUERADE #利用iptables完成NAT功能
#chmod 0666 /dev/net/tun #设置访问权限
#tunctl -t tap0 -u leemars #建立一个tap设备, 名字为tap0, 所有者为leemars
#ifconfig tap0 up #激活tap0
#ifconfig tap0 10.10.10.1 netmask 255.255.255.0 #为tap0指定IP和网段, 为10.10.10.1/24.
Guest :
网卡设置如下:
IP : 10.10.10.10
Netmask : 255.255.255.0
Gateway : 10.10.10.1
Guest -> WAN :
由Linux的iptables完成NAT功能, 提供WAN的访问服务.
Guest -> Host :
10.10.10.1是真实的Host. Guest对Host的任何访问都可以通过访问10.10.10.1来完成.
Host -> Guest :
10.10.10.10是真实的Guest. Host对Guest的任何访问都可以通过访问10.10.10.10来完成.
----------------------------------------
方案二 : Transparent Bridge (Layer 2)
生成一个网桥,然后将虚拟网卡和物理网卡用网桥连接起来.
Host :
#chmod 0666 /dev/net/tun #设置访问权限
#tunctl -t tap0 -u leemars #建立一个tap设备, 名字为tap0, 所有者为leemars
#ifconfig eth0 0.0.0.0 promisc #使eth0进入promiscuous模式
#ifconfig tap0 0.0.0.0 promisc #使tap0进入promiscuous模式
#brctl addbr br0 #增加一个网桥
#brctl addif br0 eth0 #将eth0加入网桥
#ifconfig eth0 up #激活eth0
#dhclient br0 #为br0设置IP地址
#brctl addif br0 tap0 #将tap0加入网桥
#ifconfig tap0 up #激活tap0
Guest :
网卡设置为DHCP. 或者在设置为Host的Subnet中的一个IP地址, 如下例:
IP : 192.168.1.201
Netmask : 255.255.255.0
Gateway : 192.168.1.1
可以实现主客机直接互访
-----------------------------------------------------------------------------
方案三 : Transparent IP (Layer 3) proxy ARP bridge (by parprouted)
这个我没试,因为需要parprouted这个软件的
Host :
#echo 1 > /proc/sys/net/ipv4/ip_forward #打开转发功能
#chmod 0666 /dev/net/tun #设置访问权限
#tunctl -t tap0 -u leemars #建立一个tap设备, 名字为tap0, 所有者为leemars
#ip link set tap0 up #激活tap0
#ip addr add 169.1.1.1/32 dev tap0 #为tap0任意指定一个私有地址
#parprouted [-d] ath0 tap0 #启动parprouted监听ath0和tap0. -d参数为Debug模式
Guest :
网卡设置如下:
IP : 192.168.1.201
Netmask : 255.255.255.0
Gateway : 192.168.1.1
Guest -> WAN :
由网关来提供WAN的访问服务.
Guest -> Host :
直接访问Host的IP地址即可.
Host -> Guest :
直接访问Guest的IP地址即可.
--------------------------------------------
方案四 : ARP Proxy(by Linux) + Route
通过路由来进行主客机通信的
Host :
#echo 1 > /proc/sys/net/ipv4/ip_forward #打开转发功能
#chmod 0666 /dev/net/tun #设置访问权限
#tunctl -t tap0 -u leemars #建立一个tap设备, 名字为tap0, 所有者为leemars
#ip link set tap0 up #激活tap0
#route add -host 192.168.1.201 dev tap0 #增加一个路由, 将192.168.1.201定向到tap0
#echo 1 > /proc/sys/net/ipv4/conf/ath0/proxy_arp #打开ath0上的ARP Proxy
#echo 1 > /proc/sys/net/ipv4/conf/tap0/proxy_arp #打开tap0上的ARP Proxy
Guest :
网卡设置如下:
IP : 192.168.1.201
Netmask : 255.255.255.0
Gateway : 192.168.1.1
直接可以互访了
------------------------------------------
3.Internal network
一sun工程所的Solution:
  • For every guest machine you want in your network, attach it to "Internal Network". Give the internal network a name: (Give the same name to all the guests whom you want to be in that network)
       

  • Assign a static IP address to each of your guests




虽然通过OpenVPN程序可以把两个TUN/TAP连接到一起,但是毕竟需要经过2个进程,在流量大的时候可以发现,这两个进程占用CPU比较大,可否简化一下,通过一个进程就把2个TUN/TAP设备连接到一起呢。在网上看到”Tun/Tap interface tutorial” http://backreference.org/2010/03/26/tuntap-interface-tutorial/,文章介绍如何通过程序实现与TUN/TAP设备交互,并且给了相应的实现代码。

使用作者提供的代码:http://backreference.org/wp-content/uploads/2010/03/simpletun.tar.bz2,稍作修改,实现了两个TUN/TAP连接到一起的功能。

修改后的代码如下:




/**************************************************************************
 * simpletun.c                                                            *
 *                                                                        *
 * A simplistic, simple-minded, naive tunnelling program using tun/tap    *
 * interfaces and TCP. DO NOT USE THIS PROGRAM FOR SERIOUS PURPOSES.      *
 *                                                                        *
 * You have been warned.                                                  *
 *                                                                        *
 * (C) 2010 Davide Brini.                                                 *
 *                                                                        *
 * DISCLAIMER AND WARNING: this is all work in progress. The code is      *
 * ugly, the algorithms are naive, error checking and input validation    *
 * are very basic, and of course there can be bugs. If that's not enough, *
 * the program has not been thoroughly tested, so it might even fail at   *
 * the few simple things it should be supposed to do right.               *
 * Needless to say, I take no responsibility whatsoever for what the      *
 * program might do. The program has been written mostly for learning     *
 * purposes, and can be used in the hope that is useful, but everything   *
 * is to be taken "as is" and without any kind of warranty, implicit or   *
 * explicit. See the file LICENSE for further details.                    *
 *************************************************************************/
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <net/if.h>
#include <linux/if_tun.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/time.h>
#include <errno.h>
#include <stdarg.h>
 
/* buffer for reading from tun/tap interface, must be >= 1500 */
#define BUFSIZE 2000
#define CLIENT 0
#define SERVER 1
#define PORT 55555
 
int debug;
char *progname;
 
/**************************************************************************
 * tun_alloc: allocates or reconnects to a tun/tap device. The caller     *
 *            must reserve enough space in *dev.                          *
 **************************************************************************/
int tun_alloc(char *dev, int flags) {
 
  struct ifreq ifr;
  int fd, err;
  char *clonedev = "/dev/net/tun";
 
  if( (fd = open(clonedev , O_RDWR)) < 0 ) {
    perror("Opening /dev/net/tun");
    return fd;
  }
 
  memset(&ifr, 0, sizeof(ifr));
 
  ifr.ifr_flags = flags;
 
  if (*dev) {
    strncpy(ifr.ifr_name, dev, IFNAMSIZ);
  }
 
  if( (err = ioctl(fd, TUNSETIFF, (void *)&ifr)) < 0 ) {
    perror("ioctl(TUNSETIFF)");
    close(fd);
    return err;
  }
 
  strcpy(dev, ifr.ifr_name);
 
  return fd;
}
 
/**************************************************************************
 * cread: read routine that checks for errors and exits if an error is    *
 *        returned.                                                       *
 **************************************************************************/
int cread(int fd, char *buf, int n){
 
  int nread;
 
  if((nread=read(fd, buf, n)) < 0){
    perror("Reading data");
    exit(1);
  }
  return nread;
}
 
/**************************************************************************
 * cwrite: write routine that checks for errors and exits if an error is  *
 *         returned.                                                      *
 **************************************************************************/
int cwrite(int fd, char *buf, int n){
 
  int nwrite;
 
  if((nwrite=write(fd, buf, n)) < 0){
    perror("Writing data");
    exit(1);
  }
  return nwrite;
}
 
/**************************************************************************
 * read_n: ensures we read exactly n bytes, and puts them into "buf".     *
 *         (unless EOF, of course)                                        *
 **************************************************************************/
int read_n(int fd, char *buf, int n) {
 
  int nread, left = n;
 
  while(left > 0) {
    if ((nread = cread(fd, buf, left)) == 0){
      return 0 ;
    }else {
      left -= nread;
      buf += nread;
    }
  }
  return n;
}
 
/**************************************************************************
 * do_debug: prints debugging stuff (doh!)                                *
 **************************************************************************/
void do_debug(char *msg, ...){
 
  va_list argp;
 
  if(debug) {
        va_start(argp, msg);
        vfprintf(stderr, msg, argp);
        va_end(argp);
  }
}
 
/**************************************************************************
 * my_err: prints custom error messages on stderr.                        *
 **************************************************************************/
void my_err(char *msg, ...) {
 
  va_list argp;
 
  va_start(argp, msg);
  vfprintf(stderr, msg, argp);
  va_end(argp);
}
 
/**************************************************************************
 * usage: prints usage and exits.                                         *
 **************************************************************************/
void usage(void) {
  fprintf(stderr, "Usage:\n");
  fprintf(stderr, "%s -i <ifacename> -o <ifacename> [-u|-a] [-d]\n", progname);
  fprintf(stderr, "%s -h\n", progname);
  fprintf(stderr, "\n");
  fprintf(stderr, "-i <ifacename>: Name of interface to use (mandatory)\n");
  fprintf(stderr, "-o <ifacename>: Name of interface to use (mandatory)\n");
  fprintf(stderr, "-u|-a: use TUN (-u) or TAP (-a, default)\n");
  fprintf(stderr, "-d: outputs debug information while running\n");
  fprintf(stderr, "-b: run as daemon in background\n");
  fprintf(stderr, "-h: prints this help text\n");
  exit(1);
}
 
/* for daemon */
int daemon_init(void)
{
   pid_t pid;
 
   if((pid = fork()) < 0)
        return(-1);
   else if(pid != 0)
        exit(0); /* parent exit */
/* child continues */
 
   setsid(); /* become session leader */
   chdir("/"); /* change working directory */
   umask(0); /* clear file mode creation mask */
   close(0); /* close stdin */
   close(1); /* close stdout */
   close(2); /* close stderr */
   return(0);
}
 
int main(int argc, char *argv[]) {
 
  int tap_fd, tap_fd1, option;
  int daemon_run = 0;
  int flags = IFF_TAP;
  char if_name[IFNAMSIZ] = "";
  char of_name[IFNAMSIZ] = "";
  int maxfd;
  uint16_t nread, nwrite, plength;
  char buffer[BUFSIZE];
  int cliserv = -1;    /* must be specified on cmd line */
  unsigned long int tap2net = 0, net2tap = 0;
 
  progname = argv[0];
 
  /* Check command line options */
  while((option = getopt(argc, argv, "i:o:uahdb")) > 0) {
    switch(option) {
      case 'd':
        debug = 1;
        break;
      case 'h':
        usage();
        break;
      case 'i':
        strncpy(if_name,optarg, IFNAMSIZ-1);
        break;
      case 'o':
        strncpy(of_name,optarg, IFNAMSIZ-1);
        break;
      case 'u':
        flags = IFF_TUN;
        break;
      case 'a':
        flags = IFF_TAP;
        break;
      case 'b':
        daemon_run = 1;
        break;
      default:
        my_err("Unknown option %c\n", option);
        usage();
    }
  }
 
  argv += optind;
  argc -= optind;
 
  if(argc > 0) {
    my_err("Too many options!\n");
    usage();
  }
 
  if(*if_name == '\0') {
    my_err("Must specify interface name!\n");
    usage();
  } else if(*if_name == '\0') {
    my_err("Must specify interface name!\n");
    usage();
  }
 
        /* daemon section */
    if(daemon_run && daemon_init() == -1)
    {
        printf("can't fork self\n");
        exit(0);
    }
        /* end daemon */
 
  /* initialize tun/tap interface */
  if ( (tap_fd = tun_alloc(if_name, flags | IFF_NO_PI)) < 0 ) {
    my_err("Error connecting to tun/tap interface %s!\n", if_name);
    exit(1);
  }
 
  do_debug("Successfully connected to interface %s\n", if_name);
 
  if ( (tap_fd1 = tun_alloc(of_name, flags | IFF_NO_PI)) < 0 ) {
    my_err("Error connecting to tun/tap interface %s!\n", of_name);
    exit(1);
  }
 
  do_debug("Successfully connected to interface %s\n", of_name);
 
  /* use select() to handle two descriptors at once */
  maxfd = (tap_fd > tap_fd1)?tap_fd:tap_fd1;
 
  while(1) {
    int ret;
    fd_set rd_set;
 
    FD_ZERO(&rd_set);
    FD_SET(tap_fd, &rd_set); FD_SET(tap_fd1, &rd_set);
 
    ret = select(maxfd + 1, &rd_set, NULL, NULL, NULL);
 
    if (ret < 0 && errno == EINTR){
      continue;
    }
 
    if (ret < 0) {
      perror("select()");
      exit(1);
    }
 
    if(FD_ISSET(tap_fd, &rd_set)) {
      /* data from tun/tap: just read it and write it to the network */
 
      nread = cread(tap_fd, buffer, BUFSIZE);
 
      tap2net++;
      do_debug("TAP2NET %lu: Read %d bytes from the tap interface\n", tap2net, nread);
 
      /* write length + packet */
      nwrite = cwrite(tap_fd1, buffer, nread);
 
      do_debug("TAP2NET %lu: Written %d bytes to the network\n", tap2net, nwrite);
    }
 
    if(FD_ISSET(tap_fd1, &rd_set)) {
 
      net2tap++;
 
      nread = cread(tap_fd1, buffer, BUFSIZE);
      do_debug("NET2TAP %lu: Read %d bytes from the network\n", net2tap, nread);
 
      /* now buffer[] contains a full packet or frame, write it into the tun/tap interface */
      nwrite = cwrite(tap_fd, buffer, nread);
      do_debug("NET2TAP %lu: Written %d bytes to the tap interface\n", net2tap, nwrite);
    }
  }
 
  return(0);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值