WvStreams
wvtundev.cc
00001 /* 
00002  * Worldvisions Weaver Software:
00003  *   Copyright (C) 1997-2002 Net Integration Technologies, Inc. 
00004  * 
00005  * WvTunDev provides a convenient way of using Linux tunnel devices.
00006  *
00007  * If you don't have the /dev/net/tun device, try doing: 
00008  *          mknod /dev/net/tun c 10 200
00009  */
00010 #include <sys/ioctl.h>
00011 #include <sys/socket.h> 
00012 #include "if_tun.h"
00013 #include <string.h> 
00014 
00015 #include "wvlog.h"
00016 #include "wvtundev.h"
00017 
00018 WvTunDev::WvTunDev(const WvIPNet &addr, int mtu) :
00019     WvFile("/dev/net/tun", O_RDWR)
00020 {
00021     init(addr, mtu);
00022 }
00023 
00024 void WvTunDev::init(const WvIPNet &addr, int mtu)
00025 {
00026     WvLog log("New tundev", WvLog::Debug2);
00027     if (getfd() < 0)
00028     {
00029         log("Could not open /dev/net/tun: %s\n", strerror(errno)); 
00030         seterr(errno);
00031         return;
00032     }
00033 
00034     struct ifreq ifr;
00035     memset(&ifr, 0, sizeof(ifr));
00036     ifr.ifr_flags = IFF_NO_PI | IFF_TUN;
00037 
00038     if (ioctl(getfd(), TUNSETIFF, (void *) &ifr) < 0 ||
00039         ioctl(getfd(), TUNSETNOCSUM, 1) < 0)
00040     {
00041         log("Could not initialize the interface: %s\n", strerror(errno));
00042         seterr(errno);
00043         return;
00044     }
00045     
00046     WvInterface iface(ifr.ifr_name);
00047     iface.setipaddr(addr);
00048     iface.setmtu(mtu);
00049     iface.up(true);
00050     ifcname = ifr.ifr_name;
00051     log.app = ifcname;
00052 
00053     log(WvLog::Debug2, "Now up (%s).\n", addr);
00054 }