GetComputerName和SetComputerName在Linux下的实现

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\n", THostName);
#else
        printf("utf-8--hostname:%s\n", THostName);
#endif

        return 0;
}


注:SetComputerName的可以利用sethostname以及以上方法来实现。

 
  



0
0

你可能感兴趣的:(linux,windows,内核,移植)