Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to open tap device on android using native code C?

I am trying build a VPN client mobile for Android based applications that connect to virtual infrastructure over VPN tunnel. I have a similar application for Linux/Windows and I know how to open a tun/tap device (open /dev/net/tun). How do we do the same for Android using C ?

Also what does the class VpnService in the android.net API do exactly ?

like image 986
TJ13 Avatar asked Jul 14 '14 20:07

TJ13


2 Answers

If you still wants to open a tunnel on android - native C, I suggest to take a look how android itself open it (from file: services/jni/com_android_server_connectivity_Vpn.cpp)

static int create_interface(int mtu)
{
    int tun = open("/dev/tun", O_RDWR | O_NONBLOCK);
    ifreq ifr4;
    memset(&ifr4, 0, sizeof(ifr4));
    // Allocate interface.
    ifr4.ifr_flags = IFF_TUN | IFF_NO_PI;
    if (ioctl(tun, TUNSETIFF, &ifr4)) {
        ALOGE("Cannot allocate TUN: %s", strerror(errno));
        goto error;
    }
    // Activate interface.
    ifr4.ifr_flags = IFF_UP;
    if (ioctl(inet4, SIOCSIFFLAGS, &ifr4)) {
        ALOGE("Cannot activate %s: %s", ifr4.ifr_name, strerror(errno));
        goto error;
    }
    // Set MTU if it is specified.
    ifr4.ifr_mtu = mtu;
    if (mtu > 0 && ioctl(inet4, SIOCSIFMTU, &ifr4)) {
        ALOGE("Cannot set MTU on %s: %s", ifr4.ifr_name, strerror(errno));
        goto error;
    }
    return tun;
error:
    close(tun);
    return SYSTEM_ERROR;
}
like image 58
Meir Gerenstadt Avatar answered Nov 16 '22 22:11

Meir Gerenstadt


The VpnService class does exactly what you need. It provides an access to the tun device. You cannot directly open /dev/net/tun without having root rights. See the ToyVPN example project or an open source VPN project like OpenVPN for Android.

like image 22
plaisthos Avatar answered Nov 16 '22 23:11

plaisthos