From df0d09dcb2c84a522573a5ec76cd1a91ae985cd0 Mon Sep 17 00:00:00 2001 From: "Enrico Weigelt, metux IT consult" Date: Thu, 31 Jul 2025 19:05:02 +0200 Subject: [PATCH] os: xhostname: helper for gethostname() This little helper does the OS specific part for gethostname() calls. It's putting the result into a fixed-length struct and making sure it's properly filled and the string is always zero-terminated. Signed-off-by: Enrico Weigelt, metux IT consult --- os/meson.build | 1 + os/xhostname.c | 30 ++++++++++++++++++++++++++++++ os/xhostname.h | 23 +++++++++++++++++++++++ 3 files changed, 54 insertions(+) create mode 100644 os/xhostname.c create mode 100644 os/xhostname.h diff --git a/os/meson.build b/os/meson.build index ff135b965..6257e420c 100644 --- a/os/meson.build +++ b/os/meson.build @@ -18,6 +18,7 @@ srcs_os = [ 'string.c', 'utils.c', 'xdmauth.c', + 'xhostname.c', 'xsha1.c', 'xstrans.c', 'xprintf.c', diff --git a/os/xhostname.c b/os/xhostname.c new file mode 100644 index 000000000..24b4f9ce1 --- /dev/null +++ b/os/xhostname.c @@ -0,0 +1,30 @@ +/* SPDX-License-Identifier: MIT OR X11 + * + * Copyright © 2024 Enrico Weigelt, metux IT consult + */ +#include + +#include +#include +#include + +#if WIN32 +#include +#endif + +#include "os/xhostname.h" + +int xhostname(struct xhostname* hn) +{ + /* being extra-paranoid here */ + memset(hn, 0, sizeof(struct xhostname)); + int ret = gethostname(hn->name, sizeof(hn->name)); + + if (ret == -1) { + hn->name[0] = 0; + return errno; + } + + hn->name[sizeof(hn->name)-1] = 0; + return ret; +} diff --git a/os/xhostname.h b/os/xhostname.h new file mode 100644 index 000000000..6421eaf0f --- /dev/null +++ b/os/xhostname.h @@ -0,0 +1,23 @@ +/* SPDX-License-Identifier: MIT OR X11 + * + * Copyright © 2024 Enrico Weigelt, metux IT consult + */ +#ifndef _XSERVER_OS_XHOSTNAME_H_ +#define _XSERVER_OS_XHOSTNAME_H_ + +#define XHOSTNAME_MAX 2048 + +struct xhostname { + char name[XHOSTNAME_MAX]; +}; + +/* + * retrieve host's nodename. basically a safer way of gethostname() / uname() + * making sure that the nodename is always zero-terminated. + * + * @hn pointer to struct xhostname that will be filled + * @return 0 on success + */ +int xhostname(struct xhostname* hn); + +#endif /* _XSERVER_OS_XHOSTNAME_H_ */