Pregunta

Me está costando resolver este problema, estoy tratando de escribir un programa que interactúe con el controlador del túnel de Linux. A un nivel muy básico, simplemente quiero crear una aplicación que pueda transferir datos a través de un túnel de red. Sin embargo, no sé cómo configurar correctamente el controlador del túnel para lograr esto.

Estoy desarrollando en Ubuntu 9.04, y tengo el módulo del kernel del controlador del túnel cargado.

Existe el dispositivo / dev / net / tun , sin embargo, no hay dispositivos / dev / tunX . No puedo crear estos dispositivos usando ifconfig . Cuando ejecuto / sbin / ifconfig tun0 up , por ejemplo, aparece el siguiente error:

  

tun0: ERROR al obtener indicadores de interfaz: no existe tal dispositivo.

Si intento ver el dispositivo / dev / net / tun , se presenta el siguiente error:

  

cat: / dev / net / tun: descriptor de archivo en mal estado.

Intentando abrir / dev / tunX a través de un pequeño programa, básicamente, un simple

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

devuelve -1: la aplicación se ejecuta como root y aún no puede abrir este dispositivo de túnel. Es posible abrir / dev / net / tun , sin embargo, esto no parece generar un nuevo dispositivo / dev / tunX para usar en su lugar.

En resumen, ¿cómo se hace para escribir una aplicación que desea utilizar el controlador de túnel de Linux? Cualquier información sería muy apreciada.

Gracias; ~ Robert

¿Fue útil?

Solución

Lea /usr/src/linux/Documentation/networking/tuntap.txt .

Se supone que debes abrir el dispositivo / dev / net / tun . Un subsiguiente ioctl en el fd abierto creará la interfaz de red tun0 (o como quiera que se le llame). Las interfaces de red de Linux no se corresponden con ningún dispositivo / dev / * .

Otros consejos

No hay archivos de dispositivo / dev / tunX . En su lugar, abre / dev / net / tun y configúralo a través de ioctl () para " punto " a tun0 . Para mostrar el procedimiento básico, crearé la interfaz TUN utilizando la herramienta de línea de comandos ip tun tap y luego mostraré el código C para leer desde ese dispositivo TUN. Así que para crear la interfaz de tun a través de la línea de comandos:

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

Ahora hemos creado tun0 . Para leer / escribir paquetes en esta interfaz desde un programa de espacio de usuario, debe interactuar con el archivo de dispositivo / dev / net / tun usando ioctl () . Aquí hay un ejemplo que leerá los paquetes que llegan a la interfaz tun0 e imprimirá el tamaño:

#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;
}

Me encontré con un buen tutorial de introducción sobre esto

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

Viene con un código fuente.

Estaba en el mismo conjunto de resultados de Google que esta pregunta. :-)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top