This commit is contained in:
ge
2026-04-28 23:18:57 +03:00
parent 7b17a4a33b
commit e54f013ef7
11 changed files with 142 additions and 50 deletions
+64
View File
@@ -0,0 +1,64 @@
module netio
import os
#include <net/if.h>
struct C.if_nameindex {
if_index u32
if_name &char
}
fn C.if_nametoindex(&char) u32
fn C.if_indextoname(u32, &char) &char
fn C.if_nameindex() &C.if_nameindex
fn C.if_freenameindex(voidptr)
// name_to_index translates the network interface name to index.
pub fn name_to_index(name string) !u32 {
index := C.if_nametoindex(&char(name.str))
if index == 0 {
return error('${@FN}: no index for `${name}`')
}
return index
}
// index_to_name translates the network interface index to name e.g. 'eth0'.
pub fn index_to_name(index u32) !string {
name := []u8{len: C.IF_NAMESIZE}
ifname := C.if_indextoname(index, name.data)
if isnil(ifname) {
return os.last_error()
}
return unsafe { cstring_to_vstring(ifname) }
}
pub struct NetworkInterface {
index u32
name string
}
// interfaces returns an array with names and indexes of all network interfaces in system.
pub fn interfaces() ![]NetworkInterface {
ifaces := C.if_nameindex()
if isnil(ifaces) {
return os.last_error()
}
defer {
C.if_freenameindex(ifaces)
}
mut result := []NetworkInterface{}
mut i := 0
for {
iface := unsafe { ifaces[i] }
i++
if iface.if_index == 0 && isnil(iface.if_name) {
break
}
result << NetworkInterface{
index: iface.if_index
name: unsafe { cstring_to_vstring(iface.if_name) }
}
}
return result
}