【发布时间】:2017-05-29 15:31:14
【问题描述】:
我正在尝试与 Java 中的 Linux tun 驱动程序交互,正如这里所解释的那样。
How to interface with the Linux tun driver
但是由于你不能用 java 调用 ioctl(),我使用的是 Java Native Interface。只要我不在同一个文件中读写,它就可以正常工作。
如果我这样做,我会得到这个异常,我将其翻译为“FileDescriptor 处于损坏状态”:
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)
这里是java代码:
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();
}
}
这是 C 代码:
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;
}
【问题讨论】:
-
new FileOutputStream(...)肯定会尝试创建一个新文件。尝试使用 oneRandomAccessFile而不是两个文件流。
标签: java linux java-native-interface ioctl