Prepare for choosing device name

This commit is contained in:
Erik Ekman 2006-06-24 10:21:50 +00:00
parent 57c30612a7
commit 9a6ad85240
4 changed files with 35 additions and 24 deletions

View File

@ -247,7 +247,7 @@ main(int argc, char **argv)
} }
} }
if ((tun_fd = open_tun()) == -1) if ((tun_fd = open_tun(NULL)) == -1)
goto cleanup1; goto cleanup1;
if ((dns_fd = open_dns(argv[1], 0)) == -1) if ((dns_fd = open_dns(argv[1], 0)) == -1)
goto cleanup2; goto cleanup2;

View File

@ -263,7 +263,7 @@ main(int argc, char **argv)
usage(); usage();
} }
if ((tun_fd = open_tun()) == -1) if ((tun_fd = open_tun(NULL)) == -1)
goto cleanup0; goto cleanup0;
if (tun_setip(argv[0]) != 0 || tun_setmtu(mtu) != 0) if (tun_setip(argv[0]) != 0 || tun_setmtu(mtu) != 0)
goto cleanup1; goto cleanup1;

29
tun.c
View File

@ -31,7 +31,6 @@
#define TUN_MAX_TRY 50 #define TUN_MAX_TRY 50
char *tun_device = NULL;
char if_name[50]; char if_name[50];
#ifdef LINUX #ifdef LINUX
@ -41,17 +40,15 @@ char if_name[50];
#include <linux/if_tun.h> #include <linux/if_tun.h>
int int
open_tun() open_tun(const char *tun_device)
{ {
int i; int i;
int tun_fd; int tun_fd;
struct ifreq ifreq; struct ifreq ifreq;
char *tunnel = "/dev/net/tun";
if (tun_device == NULL) if ((tun_fd = open(tunnel, O_RDWR)) < 0) {
tun_device = "/dev/net/tun"; warn("open_tun: %s: %s", tunnel, strerror(errno));
if ((tun_fd = open(tun_device, O_RDWR)) < 0) {
warn("open_tun: %s: %s", tun_device, strerror(errno));
return -1; return -1;
} }
@ -59,6 +56,20 @@ open_tun()
ifreq.ifr_flags = IFF_TUN; ifreq.ifr_flags = IFF_TUN;
if (tun_device != NULL) {
strncpy(ifreq.ifr_name, tun_device, IFNAMSIZ);
if (ioctl(tun_fd, TUNSETIFF, (void *) &ifreq) != -1) {
printf("Opened %s\n", ifreq.ifr_name);
snprintf(if_name, sizeof(if_name), "dns%d", i);
return tun_fd;
}
if (errno != EBUSY) {
warn("open_tun: ioctl[TUNSETIFF]: %s", strerror(errno));
return -1;
}
} else {
for (i = 0; i < TUN_MAX_TRY; i++) { for (i = 0; i < TUN_MAX_TRY; i++) {
snprintf(ifreq.ifr_name, IFNAMSIZ, "dns%d", i); snprintf(ifreq.ifr_name, IFNAMSIZ, "dns%d", i);
@ -75,14 +86,14 @@ open_tun()
} }
warn("open_tun: Couldn't set interface name.\n"); warn("open_tun: Couldn't set interface name.\n");
}
return -1; return -1;
} }
#else /* BSD */ #else /* BSD */
int int
open_tun() open_tun(const char *tun_device)
{ {
int i; int i;
int tun_fd; int tun_fd;

2
tun.h
View File

@ -19,7 +19,7 @@
#ifndef _TUN_H_ #ifndef _TUN_H_
#define _TUN_H_ #define _TUN_H_
int open_tun(); int open_tun(const char *);
void close_tun(int); void close_tun(int);
int write_tun(int, char *, int); int write_tun(int, char *, int);
int read_tun(int, char *, int); int read_tun(int, char *, int);