How do I find the current machine's full hostname in C (hostname and domain information)?

后端 未结 5 1707
无人共我
无人共我 2020-11-30 23:33

In a C project (POSIX), how do I get the fully qualified name for the current system?

For example, I can get just the hostname of my machine by doing gethostna

5条回答
  •  Happy的楠姐
    2020-12-01 00:22

    My solution:

    #ifdef WIN32
        #include 
        #include 
    #else
        #include 
    #endif
    
    void GetMachineName(char machineName[150])
    {
        char Name[150];
        int i=0;
    
        #ifdef WIN32
            TCHAR infoBuf[150];
            DWORD bufCharCount = 150;
            memset(Name, 0, 150);
            if( GetComputerName( infoBuf, &bufCharCount ) )
            {
                for(i=0; i<150; i++)
                {
                    Name[i] = infoBuf[i];
                }
            }
            else
            {
                strcpy(Name, "Unknown_Host_Name");
            }
        #else
            memset(Name, 0, 150);
            gethostname(Name, 150);
        #endif
        strncpy(machineName,Name, 150);
    }
    

提交回复
热议问题