tun
The tun module (built on songgao/water) creates a TUN virtual network
interface and reads/writes raw IP packets — the building block for VPNs and
custom tunnels. It requires root privileges; open fails without them.
Import it with import tun.
Functions
| Function | Signature | Description |
|---|---|---|
open | tun.open(opts?) → int | Create a TUN interface; returns a handle (-1 on error) |
read | tun.read(h: int, maxBytes: int) → string | Read raw packet bytes ("" on EOF/error) |
write | tun.write(h: int, bytes: string) → bool | Write a raw packet |
name | tun.name(h: int) → string | Interface name, e.g. "utun5" or "tun0" |
close | tun.close(h: int) → bool | Close the interface |
Example
import tun
let h = tun.open()
if h == -1 {
println("need root to open a TUN device")
exit(1)
}
println("interface: " + tun.name(h))
while true {
let packet = tun.read(h, 2048)
if packet == "" { break }
// inspect or forward the raw IP packet
}
tun.close(h)