2015-08-13 09:47:10 -07:00
|
|
|
//! @file getcomputername.cpp
|
|
|
|
|
//! @author Aaron Katz <v-aakatz@microsoft.com>
|
|
|
|
|
//! @brief Implements GetComputerName Win32 API
|
|
|
|
|
|
2015-07-30 12:46:28 -07:00
|
|
|
#include <errno.h>
|
2015-08-03 10:48:46 -07:00
|
|
|
#include <langinfo.h>
|
2015-08-13 09:47:10 -07:00
|
|
|
#include <locale.h>
|
2015-08-03 13:54:07 -07:00
|
|
|
#include <unistd.h>
|
|
|
|
|
#include <string>
|
2015-08-13 09:47:10 -07:00
|
|
|
#include "getcomputername.h"
|
2015-04-03 10:22:05 -07:00
|
|
|
|
2015-08-13 09:47:10 -07:00
|
|
|
//! @brief GetComputerName retrieves the name of the host associated with
|
|
|
|
|
//! the current thread.
|
|
|
|
|
//!
|
|
|
|
|
//! @exception errno Passes these errors via errno to GetLastError:
|
|
|
|
|
//! - ERROR_BAD_ENVIRONMENT: locale is not UTF-8
|
|
|
|
|
//! - ERROR_INVALID_FUNCTION: getlogin_r() returned an unrecognized error code
|
2015-10-27 09:19:41 -07:00
|
|
|
//! - ERROR_INVALID_ADDRESS: buffer is an invalid address
|
|
|
|
|
//! - ERROR_GEN_FAILURE: buffer not large enough
|
2015-08-13 09:47:10 -07:00
|
|
|
//!
|
2015-10-27 09:19:41 -07:00
|
|
|
//! @retval username as UTF-8 string, or null if unsuccessful
|
|
|
|
|
|
2015-10-27 10:48:31 -07:00
|
|
|
char* GetComputerName()
|
2015-04-03 10:22:05 -07:00
|
|
|
{
|
2015-07-30 12:46:28 -07:00
|
|
|
errno = 0;
|
2015-08-03 10:48:46 -07:00
|
|
|
|
|
|
|
|
// Select locale from environment
|
|
|
|
|
setlocale(LC_ALL, "");
|
|
|
|
|
// Check that locale is UTF-8
|
2015-08-14 10:51:25 -07:00
|
|
|
if (nl_langinfo(CODESET) != std::string("UTF-8"))
|
2015-08-13 10:53:09 -07:00
|
|
|
{
|
2015-08-03 10:48:46 -07:00
|
|
|
errno = ERROR_BAD_ENVIRONMENT;
|
2015-10-27 14:21:25 -07:00
|
|
|
return NULL;
|
2015-08-03 10:48:46 -07:00
|
|
|
}
|
|
|
|
|
|
2015-08-04 14:38:53 -07:00
|
|
|
// Get computername from system in a thread-safe manner
|
2015-08-14 10:51:25 -07:00
|
|
|
std::string computername(HOST_NAME_MAX, 0);
|
|
|
|
|
int err = gethostname(&computername[0], computername.length());
|
2015-08-03 13:54:07 -07:00
|
|
|
// Map errno to Win32 Error Codes
|
2015-08-13 10:53:09 -07:00
|
|
|
if (err != 0)
|
|
|
|
|
{
|
|
|
|
|
switch (errno)
|
|
|
|
|
{
|
2015-08-17 17:02:40 -07:00
|
|
|
case EFAULT:
|
|
|
|
|
errno = ERROR_INVALID_ADDRESS;
|
2015-08-03 13:54:07 -07:00
|
|
|
break;
|
2015-08-17 17:02:40 -07:00
|
|
|
case ENAMETOOLONG:
|
2015-08-21 09:55:39 -07:00
|
|
|
errno = ERROR_GEN_FAILURE;
|
2015-08-17 17:02:40 -07:00
|
|
|
break;
|
2015-08-03 13:54:07 -07:00
|
|
|
default:
|
|
|
|
|
errno = ERROR_INVALID_FUNCTION;
|
|
|
|
|
}
|
2015-10-27 14:21:25 -07:00
|
|
|
return NULL;
|
2015-08-03 13:54:07 -07:00
|
|
|
}
|
|
|
|
|
|
2015-10-27 09:19:41 -07:00
|
|
|
return strdup(computername.c_str());
|
2015-08-03 13:54:07 -07:00
|
|
|
|
2015-04-03 10:22:05 -07:00
|
|
|
}
|
2015-08-03 10:48:46 -07:00
|
|
|
|