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

TJ13 picture TJ13 · Jul 14, 2014 · Viewed 7.6k times · Source

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 ?

Answer

Meir Gerenstadt picture Meir Gerenstadt · Jan 25, 2015

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