9

I'm writing a VPN application and the socket used for the VPN Connection is handled in my native C code, not in java. How do I use VpnService.protect() on that socket? I noticed that it has a VpnService.protect(int) overload, could I return the int that socket returns from the native code to Java and protect it that way?

Example

// Native Code
int socket;

JNIEXPORT jint JNICALL
Java_com_my_package_Class_initializeSocket
(
    JNIEnv *env,
    jobject jobj
) {
    socket = socket(AF_INET, SOCK_DGRAM, 0);

    // . . . Handler other socket preparations 

    return (jint)socket;
}

// Java Code
public native int initializeSocket();

. . . 

int socket = initializeSocket();
this.protect(socket);

Edit

I did find this question that describes how the protect function works, and it looks like it might have a pretty simple implementation in C since it appears it's just using a setsockopt call. But I'm also relatively new to C so I can't quite follow how to replicate it.

Nathan F.
  • 3,250
  • 3
  • 35
  • 69
  • i didn't understand what these `VpnService.protect()` methods do. Do they keep the sockets _out_ of the VPN? – nandsito Jun 13 '17 at 11:17
  • @nandsito read this, it explains what they do: https://developer.android.com/reference/android/net/VpnService.html#protect(int) – Nathan F. Jun 13 '17 at 14:36
  • for your question, i guess you can do like you mentioned. I don't recommend doing it in C (the `setsockopt` stuff) because it would use private APIs (besides being hard as hell). If you wish you can call Java code from C, so you can call `VpnService.protect(int)` directly from C code, improving encapsulation – nandsito Jun 13 '17 at 18:09
  • 1
    @nandsito I can't avoid the socket being in C. Unfortunately, the library I'm using handles the socket and it's written in C. I do have access to the socket though. – Nathan F. Jun 13 '17 at 18:10
  • 1
    sorry, i made an amendment to my comment. It's ok to open socket in C, but i wouldn't do the `setsockopt` call. I'd either call `VpnService.protect(int)` in Java after the JNI invocation or call `VpnService.protect(int)` directly in JNI – nandsito Jun 13 '17 at 18:15

1 Answers1

7

I simply wanted verification that my processes was valid, after completing more testing I've verified that it works.

Example

// Native Code
int socket;

JNIEXPORT jint JNICALL
Java_com_my_package_Class_initializeSocket
(
    JNIEnv *env,
    jobject jobj
) {
     socket = socket(AF_INET, SOCK_DGRAM, 0);

    // . . . Handle other socket preparations 
        
    return (jint)socket;
}
// Java Code
public native int initializeSocket();
    
// . . . 

int socket = initializeSocket();
this.protect(socket);
Nathan F.
  • 3,250
  • 3
  • 35
  • 69