LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Problem with ioctl function when openning TUN/TAP device on Linux. (https://www.linuxquestions.org/questions/linux-newbie-8/problem-with-ioctl-function-when-openning-tun-tap-device-on-linux-831296/)

shmilt24 09-09-2010 09:29 PM

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

estabroo 09-09-2010 10:32 PM

What's the error it's returning? You can check errno or use something like perror

alan99 09-10-2010 02:14 AM

I'm not too clear on this code, but why are you typecasting &ifr with (void *). is ifr an enumerated type?


All times are GMT -5. The time now is 10:41 PM.