-->

如何使用Linux的TUN驱动接口(How to interface with the Linux

2019-06-23 10:24发布

我有一个很难搞清楚这个问题了 - 我想编写一个程序,都可以使用Linux驱动程序的隧道进行交互。 在一个非常基本的水平,我只是想创建一个应用程序,它能够在网络上的隧道传输数据。 然而,我在一个不知如何才能做到这一点正确设置通道驱动程序是完全。

我开发在Ubuntu 9.04,和我有隧道驱动内核模块加载。

存在的设备/dev/net/tun ,但是不存在/dev/tunX设备。 我无法创建使用这些设备的ifconfig -每当我运行/sbin/ifconfig tun0 up ,例如,我得到以下错误:

TUN0:在获取接口标志错误:没有这样的设备。

如果我尝试一下/dev/net/tun设备,提出了以下错误:

猫是:/ dev /网/ TUN:在状态不好的文件描述符。

试图打开/dev/tunX通过一个小程序,基本上,一个简单的

tun_fd = open( "/dev/tun0", O_RDWR )

返回-1:应用程序正在运行为根,并且仍然不能打开此隧道设备。 它是可以打开/dev/net/tun ,但是这似乎并没有产生新/dev/tunX设备改为使用。

因此,在总结 - 一个人如何去写希望使用Linux的隧道司机的应用程序? 任何见解将不胜感激。

谢谢; 〜罗伯特

Answer 1:

阅读/usr/src/linux/Documentation/networking/tuntap.txt

你应该open/dev/net/tun设备。 随后ioctl就开FD将创建tun0 (或任何你想将它命名)网络接口。 Linux的网络接口不对应任何/dev/*设备。



Answer 2:

有没有/dev/tunX设备文件。 相反,你打开/dev/net/tun ,并通过配置它ioctl()以“点”到tun0 。 要显示的基本步骤,我将创建使用命令行工具TUN接口ip tun tap然后显示该C代码从TUN设备读取。 因此,要通过创建命令行界面囤:

sudo ip tuntap add mode tun dev tun0
ip addr add 10.0.0.0/24 dev tun0  # give it an ip
ip link set dev tun0 up  # bring the if up
ip route get 10.0.0.2  # check that packets to 10.0.0.x are going through tun0
ping 10.0.0.2  # leave this running in another shell to be able to see the effect of the next example

现在我们有tun0创建。 为了从你需要的交互的用户空间程序读取/写入数据包到该接口/dev/net/tun使用设备文件ioctl() 这里是将读取到达数据包的例子tun0接口和打印尺寸:

#include <fcntl.h>  /* O_RDWR */
#include <string.h> /* memset(), memcpy() */
#include <stdio.h> /* perror(), printf(), fprintf() */
#include <stdlib.h> /* exit(), malloc(), free() */
#include <sys/ioctl.h> /* ioctl() */

/* includes for struct ifreq, etc */
#include <sys/types.h>
#include <sys/socket.h>
#include <linux/if.h>
#include <linux/if_tun.h>

int tun_open(char *devname)
{
  struct ifreq ifr;
  int fd, err;

  if ( (fd = open("/dev/net/tun", O_RDWR)) == -1 ) {
       perror("open /dev/net/tun");exit(1);
  }
  memset(&ifr, 0, sizeof(ifr));
  ifr.ifr_flags = IFF_TUN;
  strncpy(ifr.ifr_name, devname, IFNAMSIZ); // devname = "tun0" or "tun1", etc 

  /* ioctl will use ifr.if_name as the name of TUN 
   * interface to open: "tun0", etc. */
  if ( (err = ioctl(fd, TUNSETIFF, (void *) &ifr)) == -1 ) {
    perror("ioctl TUNSETIFF");close(fd);exit(1);
  }

  /* After the ioctl call the fd is "connected" to tun device specified
   * by devname ("tun0", "tun1", etc)*/

  return fd;
}


int main(int argc, char *argv[])
{
  int fd, nbytes;
  char buf[1600];

  fd = tun_open("tun0"); /* devname = ifr.if_name = "tun0" */
  printf("Device tun0 opened\n");
  while(1) {
    nbytes = read(fd, buf, sizeof(buf));
    printf("Read %d bytes from tun0\n", nbytes);
  }
  return 0;
}


Answer 3:

我碰到一个不错的介绍教程来到这个

http://backreference.org/2010/03/26/tuntap-interface-tutorial/

它配备了一个源码包。

这是在同一组谷歌的结果这个问题。 :-)



文章来源: How to interface with the Linux tun driver