Commit e63daca92e

Andrew Kelley <andrew@ziglang.org>
2019-09-12 03:21:00
linux implementation of std.net.getHostName
1 parent 8a15537
Changed files (4)
std/os/bits/linux.zig
@@ -1175,3 +1175,13 @@ pub const IORING_REGISTER_FILES = 2;
 pub const IORING_UNREGISTER_FILES = 3;
 pub const IORING_REGISTER_EVENTFD = 4;
 pub const IORING_UNREGISTER_EVENTFD = 5;
+
+pub const utsname = extern struct {
+    sysname: [65]u8,
+    nodename: [65]u8,
+    release: [65]u8,
+    version: [65]u8,
+    machine: [65]u8,
+    domainname: [65]u8,
+};
+pub const HOST_NAME_MAX = 64;
std/os/linux.zig
@@ -965,6 +965,10 @@ pub fn sigaltstack(ss: ?*stack_t, old_ss: ?*stack_t) usize {
     return syscall2(SYS_sigaltstack, @ptrToInt(ss), @ptrToInt(old_ss));
 }
 
+pub fn uname(uts: *utsname) usize {
+    return syscall1(SYS_uname, @ptrToInt(uts));
+}
+
 // XXX: This should be weak
 extern const __ehdr_start: elf.Ehdr = undefined;
 
std/net.zig
@@ -245,3 +245,11 @@ pub fn connectUnixSocket(path: []const u8) !std.fs.File {
 
     return std.fs.File.openHandle(sockfd);
 }
+
+pub const getHostName = os.gethostname;
+
+test "getHostName" {
+    var buf: [os.HOST_NAME_MAX]u8 = undefined;
+    const hostname = try getHostName(&buf);
+    expect(hostname.len != 0);
+}
std/os.zig
@@ -2688,6 +2688,28 @@ pub fn futimens(fd: fd_t, times: *const [2]timespec) FutimensError!void {
     }
 }
 
+pub const GetHostNameError = error{Unexpected};
+
+pub fn gethostname(name_buffer: *[HOST_NAME_MAX]u8) GetHostNameError![]u8 {
+    if (builtin.link_libc) {
+        @compileError("TODO implement gethostname when linking libc");
+    }
+    if (linux.is_the_target) {
+        var uts: utsname = undefined;
+        switch (errno(system.uname(&uts))) {
+            0 => {
+                const hostname = mem.toSlice(u8, &uts.nodename);
+                mem.copy(u8, name_buffer, hostname);
+                return name_buffer[0..hostname.len];
+            },
+            EFAULT => unreachable,
+            else => |err| return unexpectedErrno(err),
+        }
+    }
+
+    @compileError("TODO implement gethostname for this OS");
+}
+
 test "" {
     _ = @import("os/darwin.zig");
     _ = @import("os/freebsd.zig");