Files
PowerShell/native/getcomputername.cpp
T

47 lines
1.3 KiB
C++
Raw Normal View History

//! @file getcomputername.cpp
2015-10-27 15:33:25 -07:00
//! @author George Fleming <v-geflem@microsoft>
//! @brief Implements GetComputerName Win32 API
2015-07-30 12:46:28 -07:00
#include <errno.h>
2015-08-03 13:54:07 -07:00
#include <unistd.h>
#include <string>
#include "getcomputername.h"
//! @brief GetComputerName retrieves the name of the host associated with
//! the current thread.
//!
//! @exception errno Passes these errors via errno to GetLastError:
//! - 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-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()
{
errno = 0;
2015-11-09 09:51:06 -08:00
// Get computername from system, note that gethostname(2) gets the
// nodename from uname
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:
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
}