const SetLink = @import("SetLink.zig"); const SetLinkAttr = @import("SetLinkAttr.zig"); const netlink = @import("netlink"); const std = @import("std"); const mem = std.mem; const linux = std.os.linux; const Io = std.Io; socket: netlink.Socket, const Self = @This(); pub fn init() !Self { return .{ .socket = try netlink.Socket.init(linux.NETLINK.ROUTE), }; } pub fn deinit(self: *Self, io: Io) void { self.socket.deinit(io); self.* = undefined; } pub fn setLink(self: *Self, io: Io, ifindex: i32, up: bool) !void { const sl = try SetLink.init(ifindex, up); try self.request(io, &sl); } pub fn setLinkAttr(self: *Self, io: Io, ifindex: i32, attr: SetLinkAttr.Attr) !void { const sla = try SetLinkAttr.init(ifindex, attr); try self.request(io, &sla); } fn request(self: *Self, io: Io, req: anytype) !void { const seq = try self.socket.send(io, linux.NetlinkMessageType.RTM_SETLINK, req); var buf: [32 * 1024]u8 = undefined; while (true) { var it: netlink.Message.Iterator = .{ .buf = try self.socket.receive(io, &buf) }; while (try it.next()) |msg| { if (msg.header.seq != seq) continue; switch (msg.header.type) { linux.NetlinkMessageType.ERROR => { if (msg.payload.len < @sizeOf(i32)) return error.Malformed; const code = mem.readInt(i32, msg.payload[0..4], .native); return switch (@as(linux.E, @fromBackingInt(@intCast(-code)))) { .SUCCESS => return, .NODEV => error.NoSuchInterface, .PERM => error.PermissionDenied, .RFKILL => error.RfKilled, else => error.NetlinkError, }; }, else => {}, } } } }