I am trying to interface with the Linux tun driver in Java as it is explained here.
How to interface with the Linux tun driver
But since you can not call ioctl() with java, I am using the Java Native Interface. It is working fine as long as I don't read and write in the same file.
If I do so I get this exception, which I would translate by "The FileDescriptor is in a broken state" :
java.io.IOException: Le descripteur du fichier est dans un mauvais état
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:326)
at WriterThread.main(WriterThread.java:54)
Here is the java code :
public static void main(String[] arg){
File tunFile = new File("/dev/net/tun");
FileOutputStream outStream;
FileInputStream inStream;
try {
inStream = new FileInputStream(tunFile);
outStream = new FileOutputStream(tunFile);
FileDescriptor fd = inStream.getFD();
//getting the file descriptor
Field f = fd.getClass().getDeclaredField("fd");
f.setAccessible(true);
int descriptor = f.getInt(fd);
//use of Java Native Interface
new TestOuvertureFichier().ioctl(descriptor);
while(true){
System.out.println("reading");
byte[] bytes = new byte[500];
int l = 0;
l = inStream.read(bytes);
//the problem seems to come from here
outStream.write(bytes,0,l);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Here is the C code :
JNIEXPORT void JNICALL Java_TestOuvertureFichier_ioctl(JNIEnv *env,jobject obj, jint descriptor){
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = IFF_TUN;
strncpy(ifr.ifr_name, "tun0", IFNAMSIZ);
int err;
if ( (err = ioctl(descriptor, TUNSETIFF, (void *) &ifr)) == -1 ) {
perror("ioctl TUNSETIFF");exit(1);
}
return;
}