You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Zig v0.12版本如何获取主机名?原std.os.gethostname已移除

在Zig v0.12+中获取本机主机名的方法

方案一:使用std.os.uname(无需链接libc,类Unix系统适用)

Zig v0.12移除std.os.gethostname后,标准库提供了std.os.uname来获取系统信息,其中包含主机名字段,这是无需依赖libc的原生方案:

const std = @import("std");
const os = std.os;

pub fn main() !void {
    const sys_info = try os.uname();
    std.debug.print("主机名: {s}\n", .{sys_info.nodename});
}

方案二:使用std.c.gethostname(需链接libc)

如果偏好使用gethostname接口,可通过std.c调用,但必须在编译时链接libc:

const std = @import("std");
const c = std.c;
const os = std.os;

pub fn main() !void {
    var hostname_buf: [256]u8 = undefined;
    const err = c.gethostname(&hostname_buf, hostname_buf.len);
    if (err != 0) return os.unexpectedErrno(@intCast(err));
    
    std.debug.print("主机名: {s}\n", .{hostname_buf});
}

编译时需添加-lc参数:

zig build-exe your_file.zig -lc

方案三:Windows平台专属原生方法(无需链接libc)

类Unix的uname在Windows上不可用,可直接调用Windows系统API获取主机名:

const std = @import("std");
const windows = std.os.windows;

pub fn main() !void {
    var hostname_buf: [windows.MAX_COMPUTERNAME_LENGTH + 1]u16 = undefined;
    var buf_length: u32 = hostname_buf.len;

    const success = windows.GetComputerNameW(&hostname_buf, &buf_length);
    if (success == 0) return windows.unexpectedError(windows.kernel32.GetLastError());

    const hostname = try std.unicode.utf16leToUtf8Alloc(std.heap.page_allocator, hostname_buf[0..buf_length]);
    defer std.heap.page_allocator.free(hostname);

    std.debug.print("主机名: {s}\n", .{hostname});
}

内容的提问来源于stack exchange,提问作者Luxcih

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 08:52:37