Linux tun ドライバーとのインターフェース方法

/dev/tunX はありません デバイスファイル。代わりに、/dev/net/tun を開きます ioctl() で設定します tun0 を「指す」 .基本的な手順を示すために、コマンド ライン ツール ip tun tap を使用して TUN インターフェイスを作成します。 次に、その TUN デバイスから読み取る 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;
}

/usr/src/linux/Documentation/networking/tuntap.rst を読む .

open することになっています /dev/net/tun デバイス。その後の ioctl 開いている fd で tun0 を作成します (または任意の名前を付けます)ネットワークインターフェイス。 Linux のネットワーク インターフェイスはどの /dev/* にも対応していません


これについての素晴らしい入門チュートリアルを見つけました

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

ソース tarball が付属しています。

この質問と同じ一連の Google 検索結果に含まれていました。 :-)