aboutsummaryrefslogtreecommitdiff
path: root/util/oslib-posix.c
diff options
context:
space:
mode:
authorMichal Privoznik <mprivozn@redhat.com>2020-06-22 20:19:35 +0200
committerMichael Roth <mdroth@linux.vnet.ibm.com>2020-07-13 17:44:58 -0500
commite47f4765afcab2b78dfa5b0115abf64d1d49a5d3 (patch)
tree742e33d46437b3f323f14290732020d1e9df05d0 /util/oslib-posix.c
parent844bd70b5652f30bbace89499f513e3fbbb6457a (diff)
downloadqemu-e47f4765afcab2b78dfa5b0115abf64d1d49a5d3.zip
qemu-e47f4765afcab2b78dfa5b0115abf64d1d49a5d3.tar.gz
qemu-e47f4765afcab2b78dfa5b0115abf64d1d49a5d3.tar.bz2
util: Introduce qemu_get_host_name()
This function offers operating system agnostic way to fetch host name. It is implemented for both POSIX-like and Windows systems. Signed-off-by: Michal Privoznik <mprivozn@redhat.com> Reviewed-by: Philippe Mathieu-Daudé <philmd@redhat.com> Reviewed-by: Daniel P. Berrangé <berrange@redhat.com> Cc: qemu-stable@nongnu.org Signed-off-by: Michael Roth <mdroth@linux.vnet.ibm.com>
Diffstat (limited to 'util/oslib-posix.c')
-rw-r--r--util/oslib-posix.c35
1 files changed, 35 insertions, 0 deletions
diff --git a/util/oslib-posix.c b/util/oslib-posix.c
index 72907d4..e60aea8 100644
--- a/util/oslib-posix.c
+++ b/util/oslib-posix.c
@@ -794,3 +794,38 @@ void sigaction_invoke(struct sigaction *action,
}
action->sa_sigaction(info->ssi_signo, &si, NULL);
}
+
+#ifndef HOST_NAME_MAX
+# ifdef _POSIX_HOST_NAME_MAX
+# define HOST_NAME_MAX _POSIX_HOST_NAME_MAX
+# else
+# define HOST_NAME_MAX 255
+# endif
+#endif
+
+char *qemu_get_host_name(Error **errp)
+{
+ long len = -1;
+ g_autofree char *hostname = NULL;
+
+#ifdef _SC_HOST_NAME_MAX
+ len = sysconf(_SC_HOST_NAME_MAX);
+#endif /* _SC_HOST_NAME_MAX */
+
+ if (len < 0) {
+ len = HOST_NAME_MAX;
+ }
+
+ /* Unfortunately, gethostname() below does not guarantee a
+ * NULL terminated string. Therefore, allocate one byte more
+ * to be sure. */
+ hostname = g_new0(char, len + 1);
+
+ if (gethostname(hostname, len) < 0) {
+ error_setg_errno(errp, errno,
+ "cannot get hostname");
+ return NULL;
+ }
+
+ return g_steal_pointer(&hostname);
+}