Reputation: 3163
I have written the following function that is supposed to create a TUN interface named "my_tun" on Linux:
int tun_open()
{
int fd;
if ((fd = open("/dev/net/tun", O_RDWR)) == -1) {
return -1;
}
struct ifreq ifr;
strncpy(ifr.ifr_name, "my_tun", IFNAMSIZ);
ifr.ifr_flags = IFF_TUN | IFF_NO_PI;
if (ioctl(fd, TUNSETIFF, &ifr) == -1) {
return -1;
}
return fd;
}
I'm testing it by running it inside a Ubuntu docker container started with --cap-add NET_ADMIN
. Inside this docker container I first execute:
mkdir /dev/net
mknod /dev/net/tun c 10 200
And the run my function. The latter does not fail yet afterwards ifconfig
does not show a TUN interface, only an ethernet and a loopback interface. What am I doing wrong?
Upvotes: 0
Views: 727
Reputation: 1
By using the code you provided, a non persistent TUN interface would be created and, after your program exits, the TUN interface will be destroyed.
You can make it persistent by adding this to your code:
int result = ioctl(fd, TUNSETPERSIST, 1);
if (result == -1)
{
printf("Unable to make TUN interface persistent\n");
}
Make sure to include if_tun.h
for TUNSETPERSIST
.
Upvotes: 0
Reputation: 33
Try "ip link" and you might see it there provided code above didn't return -1. Also your interface is non-persistent therefore you need to keep the program running when u try ifconfig or IP link. Try to add a sleep before "return fd" to buy time and see if that helps.
Upvotes: 0
Reputation: 12708
I recommend you to check the source code of ifconfig
tool. It should contain correct code to create tun
devices. Use it as reference.
Most probably, the newest edition of "UNIX Network Programming" (Stevens et al.) should have a description somewher on how to create a tun device also.
Upvotes: 0