summaryrefslogtreecommitdiffstats
path: root/qga
diff options
context:
space:
mode:
Diffstat (limited to 'qga')
-rw-r--r--qga/commands-common.h11
-rw-r--r--qga/commands-posix.c35
-rw-r--r--qga/commands-win32.c13
-rw-r--r--qga/commands.c2
4 files changed, 60 insertions, 1 deletions
diff --git a/qga/commands-common.h b/qga/commands-common.h
index 90785ed4bb..d0e4a9696f 100644
--- a/qga/commands-common.h
+++ b/qga/commands-common.h
@@ -18,4 +18,15 @@ GuestFileHandle *guest_file_handle_find(int64_t id, Error **errp);
GuestFileRead *guest_file_read_unsafe(GuestFileHandle *gfh,
int64_t count, Error **errp);
+/**
+ * qga_get_host_name:
+ * @errp: Error object
+ *
+ * Operating system agnostic way of querying host name.
+ * Compared to g_get_host_name(), it doesn't cache the result.
+ *
+ * Returns allocated hostname (caller should free), NULL on failure.
+ */
+char *qga_get_host_name(Error **errp);
+
#endif
diff --git a/qga/commands-posix.c b/qga/commands-posix.c
index 390c1560e1..77f4672ca2 100644
--- a/qga/commands-posix.c
+++ b/qga/commands-posix.c
@@ -3278,3 +3278,38 @@ GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
return 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 *qga_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);
+}
diff --git a/qga/commands-win32.c b/qga/commands-win32.c
index 406e4072a0..d56b5fd2a7 100644
--- a/qga/commands-win32.c
+++ b/qga/commands-win32.c
@@ -2519,3 +2519,16 @@ GuestDeviceInfoList *qmp_guest_get_devices(Error **errp)
}
return head;
}
+
+char *qga_get_host_name(Error **errp)
+{
+ wchar_t tmp[MAX_COMPUTERNAME_LENGTH + 1];
+ DWORD size = G_N_ELEMENTS(tmp);
+
+ if (GetComputerNameW(tmp, &size) == 0) {
+ error_setg_win32(errp, GetLastError(), "failed close handle");
+ return NULL;
+ }
+
+ return g_utf16_to_utf8(tmp, size, NULL, NULL, NULL);
+}
diff --git a/qga/commands.c b/qga/commands.c
index 4e9ce25b2e..690da0073d 100644
--- a/qga/commands.c
+++ b/qga/commands.c
@@ -511,7 +511,7 @@ int ga_parse_whence(GuestFileWhence *whence, Error **errp)
GuestHostName *qmp_guest_get_host_name(Error **errp)
{
GuestHostName *result = NULL;
- g_autofree char *hostname = qemu_get_host_name(errp);
+ g_autofree char *hostname = qga_get_host_name(errp);
/*
* We want to avoid using g_get_host_name() because that