LinuxでのGetComputerNameとSetComputerNameの実装


Windows環境での定義:
//          
BOOL WINAPI GetComputerName(
  _Out_    LPTSTR lpBuffer,
  _Inout_  LPDWORD lpnSize
);

Linuxでの対応の実装:
 
  
#include <stdio.h>
#include <unistd.h>//gethostname
#include <limits.h>//HOST_NAME_MAX 
#include <stdlib.h>//mbstowcs new delete
#include <wchar.h>//wprintf
typedef unsigned int        DWORD, *PDWORD;

#ifdef UNICODE
typedef wchar_t                         TCHAR, *PTCHAR;
#else
typedef char                                                    TCHAR, *PTCHAR;
#endif

bool GetComputerName(PTCHAR lpBuffer, PDWORD lpnSize)
{
#ifdef UNICODE
        //char *cName = (char *)malloc( (*lpnSize) * sizeof(char) );
        char *cName = new char[lpnSize];

        if(cName == NULL)
        {
                return false;
        }

        if(gethostname(cName, *lpnSize) == 0)
        {
                //char* -> wchar_t*
                if( mbstowcs(lpBuffer, cName, *lpnSize) != -1 )
                {
                        delete [] cName;
                        return true;
                }
        }

        delete [] cName;
        return false;
#else
        if(gethostname(lpBuffer, *lpnSize) == 0)
        {
                return true;
        }
        return false;
#endif
}


int main()
{
        DWORD DSize = HOST_NAME_MAX + 1;
        TCHAR THostName[DSize];

        if(!GetComputerName(THostName, &DSize))
        {
                //error
        }
#ifdef UNICODE
        //printf("");
        wprintf(L"unicode--hostname:%ls
", THostName); #else printf("utf-8--hostname:%s
", THostName); #endif return 0; }

:SetComputerNameはsethostnameおよび の で できます.
 
  



0
0