Problem with ioctl function when openning TUN/TAP device on Linux.
Hi all,
I have just study about using TUN/TAP. I tried to write a small program to open TUN (source code as the following), but the result is always : ioctl on TUNSETIFF failed. That means the function ioctl always return error. I don't know why.
Somebody can help me to solve this problem ? Thank you very much.
int tun_open (char *name)
{
struct ifreq ifr;
int err, fd;
// struct ip_tunnel_parm p;
if ((fd = open ("/dev/net/tun", O_RDWR)) < 0)
{
printf ("%s\n", name);
return -1;
}
memset (&ifr, 0, sizeof (ifr));
/* Flags: IFF_TUN - TUN device (no Ethernet headers)
* IFF_TAP - TAP device
*
* IFF_NO_PI - Do not provide packet information
*/
ifr.ifr_flags = IFF_TUN;
if (*name)
strncpy (ifr.ifr_name, name, IFNAMSIZ);
if ((err = ioctl (fd, TUNSETIFF, (void *) &ifr)) < 0)
{
close (fd);
printf ("ioctl on TUNSETIFF failed %d\n", err);
return err;
}
strncpy (name, ifr.ifr_name, IFNAMSIZ); // the name actually allocated
printf ("Opened %s\n", name);
return fd;
}
int main ()
{
int tun_fd, nread, i;
char name[10] = "tun0";
tun_fd = tun_open (name); /* tun interface */
exit(0);
}
|