4

I'm trying open a TUN device in a Linux (hopefully ultimately in a Java application). Since I don't want to use any native code (I want to avoid JNI if possible) I want to do as much as possible through the commandline. Here's what I'm trying to do:

  • Create a TUN interface using ip tuntap add dev tun0 mode tun
  • Set it to up, and give it an IP address (simple enough with the ip command)
  • Open some kind of /dev/tun0 file to write traffic from the network side.

The last step is where I'm a little confused - I gather this would work on Unix because network adapters are files, but I'm on Linux and I don't think I can access NICs that way. I understand this is simple with native code (make a few calls to ioctl and get a file descriptor) but unless there's some way to do that from the commandline it won't work.

Is there any way I can open an already configured tun interface (configured with ip tuntap) with an open call, and start writing network-side IP packets to it (without using ioctl)?

Matt Lyons-Wood
  • 931
  • 11
  • 17

1 Answers1

4

If you've set it up via ip tuntap, then you can just open it as a read/write file form java and then write whole ethernet packets to it. You can open it twice (FileInputStream/FileOutputStream) to read and write ethernet packets to it.

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40
  • 1
    How do I open it though? `new FileInputStream("/dev/net/tun0")` will (presumably) return File Not Found (I've only checked with `ls` though) – Matt Lyons-Wood Aug 24 '12 at 01:13
  • Ah, indeed - sorry, just read up on TUN and it doesn't create an actual device file. You will need to write some C code, unfortunately. If you don't want to write JNI code, you could create a program that opens the device and bridges the new file descriptor with its STDIN/STDOUT; see http://stackoverflow.com/questions/11336157/running-external-program-with-redirected-stdin-and-stdout-from-java on how to interface this with Java. – Tassos Bassoukos Aug 24 '12 at 10:15
  • You're right - I didn't read [this](http://backreference.org/2010/03/26/tuntap-interface-tutorial/) properly, it turns out your process still has to open the interface with some ioctl calls even after you've set it up with `ip tuntap`. Looks like I'll have to man up and learn JNI :) – Matt Lyons-Wood Aug 25 '12 at 13:59