Skip to content

Instantly share code, notes, and snippets.

@dgv
Created September 6, 2024 05:37
Show Gist options
  • Save dgv/12e48b61bef85525fe7fab0feca0d4a0 to your computer and use it in GitHub Desktop.
Save dgv/12e48b61bef85525fe7fab0feca0d4a0 to your computer and use it in GitHub Desktop.
Zig Wake-On-Lan Script
// compile it with: zig build-exe wol.zig
// run it with: zig run wol.zig -- <mac-address>
const std = @import("std");
pub fn main() !void {
//var buf: [13]u8 = undefined;
//var fba = std.heap.FixedBufferAllocator.init(&buf);
const args = try std.process.argsAlloc(std.heap.page_allocator);
if (args.len != 2 or args[1].len != 17) {
std.debug.print("usage: {s} <mac-address>\n\t{s} 01:02:03:04:05:06\n", .{ args[0], args[0] });
return;
}
// https://en.wikipedia.org/wiki/Wake-on-LAN#Magic_packet
var magic_packet = try std.ArrayList(u8).initCapacity(std.heap.page_allocator, 102);
defer magic_packet.deinit();
try magic_packet.appendSlice(&.{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff });
for (0..16) |_| try magic_packet.appendSlice(&.{ try std.fmt.parseUnsigned(u8, args[1][0..2], 16), try std.fmt.parseUnsigned(u8, args[1][3..5], 16), try std.fmt.parseUnsigned(u8, args[1][6..8], 16), try std.fmt.parseUnsigned(u8, args[1][9..11], 16), try std.fmt.parseUnsigned(u8, args[1][12..14], 16), try std.fmt.parseUnsigned(u8, args[1][15..17], 16) });
const sockfd = try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM | std.posix.SOCK.CLOEXEC, 0);
defer std.posix.close(sockfd);
try std.posix.setsockopt(sockfd, std.posix.SOL.SOCKET, std.posix.SO.BROADCAST, &std.mem.toBytes(@as(c_int, 1)));
const addr = try std.net.Address.resolveIp("255.255.255.255", 9);
try std.posix.connect(sockfd, &addr.any, addr.getOsSockLen());
_ = try std.posix.send(sockfd, magic_packet.items, 0);
std.debug.print("Wake-On-Lan packet was sent to {s}\n", .{args[1]});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment