windows: add GetComputerNameA so that hostname-related functions work

This commit is contained in:
Jeffrey C. Ollie
2026-03-05 10:03:58 -06:00
parent d29e1cc137
commit b1d3e36e2e
2 changed files with 36 additions and 6 deletions

View File

@@ -1,4 +1,5 @@
const std = @import("std");
const builtin = @import("builtin");
const posix = std.posix;
pub const LocalHostnameValidationError = error{
@@ -99,9 +100,21 @@ pub fn isLocal(hostname: []const u8) LocalHostnameValidationError!bool {
if (std.mem.eql(u8, "localhost", hostname)) return true;
// If hostname is not "localhost" it must match our hostname.
var buf: [posix.HOST_NAME_MAX]u8 = undefined;
const ourHostname = try posix.gethostname(&buf);
return std.mem.eql(u8, hostname, ourHostname);
switch (builtin.os.tag) {
.windows => {
const windows = @import("windows.zig");
var buf: [256:0]u8 = undefined;
var nSize: windows.DWORD = buf.len;
if (windows.exp.kernel32.GetComputerNameA(&buf, &nSize) == 0) return false;
const ourHostname = buf[0..nSize];
return std.mem.eql(u8, hostname, ourHostname);
},
else => {
var buf: [posix.HOST_NAME_MAX]u8 = undefined;
const ourHostname = try posix.gethostname(&buf);
return std.mem.eql(u8, hostname, ourHostname);
},
}
}
test "isLocal returns true when provided hostname is localhost" {
@@ -109,9 +122,21 @@ test "isLocal returns true when provided hostname is localhost" {
}
test "isLocal returns true when hostname is local" {
var buf: [posix.HOST_NAME_MAX]u8 = undefined;
const localHostname = try posix.gethostname(&buf);
try std.testing.expect(try isLocal(localHostname));
switch (builtin.os.tag) {
.windows => {
const windows = @import("windows.zig");
var buf: [256:0]u8 = undefined;
var nSize: windows.DWORD = buf.len;
if (windows.exp.kernel32.GetComputerNameA(&buf, &nSize) == 0) return error.GetComputerNameFailed;
const localHostname = buf[0..nSize];
try std.testing.expect(try isLocal(localHostname));
},
else => {
var buf: [posix.HOST_NAME_MAX]u8 = undefined;
const localHostname = try posix.gethostname(&buf);
try std.testing.expect(try isLocal(localHostname));
},
}
}
test "isLocal returns false when hostname is not local" {

View File

@@ -99,6 +99,11 @@ pub const exp = struct {
lpStartupInfo: *windows.STARTUPINFOW,
lpProcessInformation: *windows.PROCESS_INFORMATION,
) callconv(.winapi) windows.BOOL;
/// https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-getcomputernamea
pub extern "kernel32" fn GetComputerNameA(
lpBuffer: windows.LPSTR,
nSize: *windows.DWORD,
) callconv(.winapi) windows.BOOL;
};
pub const PROC_THREAD_ATTRIBUTE_NUMBER = 0x0000FFFF;