Skip to content
Snippets Groups Projects
Commit e47f4765 authored by Michal Privoznik's avatar Michal Privoznik Committed by Michael Roth
Browse files

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: default avatarMichal Privoznik <mprivozn@redhat.com>
Reviewed-by: default avatarPhilippe Mathieu-Daudé <philmd@redhat.com>
Reviewed-by: default avatarDaniel P. Berrangé <berrange@redhat.com>
Cc: qemu-stable@nongnu.org
Signed-off-by: default avatarMichael Roth <mdroth@linux.vnet.ibm.com>
parent 844bd70b
No related branches found
No related tags found
No related merge requests found
......@@ -655,4 +655,14 @@ static inline void qemu_reset_optind(void)
#endif
}
/**
* qemu_get_host_name:
* @errp: Error object
*
* Operating system agnostic way of querying host name.
*
* Returns allocated hostname (caller should free), NULL on failure.
*/
char *qemu_get_host_name(Error **errp);
#endif
......@@ -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);
}
......@@ -808,3 +808,16 @@ bool qemu_write_pidfile(const char *filename, Error **errp)
}
return true;
}
char *qemu_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);
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment