Search code examples
c++windowsip-addresshostname

Get computername from hostname in C++?


The IP address is 192.168.23.4. I am able to get the hostname from the ipaddress using the following code snippet:

struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];
inet_pton(AF_INET, "192.168.23.4", &(sa.sin_addr));

struct sockaddr_in saGNI;
char hostname[NI_MAXHOST];
char servInfo[NI_MAXSERV];
u_short port = 27015;
saGNI.sin_family = AF_INET;
saGNI.sin_addr.s_addr = sa.sin_addr.s_addr;
saGNI.sin_port = htons(port);

DWORD dwRetval = getnameinfo((struct sockaddr *) &saGNI,
    sizeof(struct sockaddr),
    hostname,
    NI_MAXHOST, servInfo, NI_MAXSERV, NI_NUMERICSERV);
printf("HostName: %s", hostname);

I am getting an output of the form

ComputerName.domain.com

How do I get the Computername from the hostname?

Eg Input

ComputerName.domain.com

Eg Output

ComputerName

Is there any way to directly get the ComputerName of a system whose IP address is known?

I am looking for the same result as displayed using the Hostname command on the remote system.


Solution

  • As suggested by emirc, the following code is printing Computername:

    struct sockaddr_in sa;
    char str[INET_ADDRSTRLEN];
    inet_pton(AF_INET, "192.168.23.4", &(sa.sin_addr));
    
    struct sockaddr_in saGNI;
    char hostname[NI_MAXHOST];
    char servInfo[NI_MAXSERV];
    u_short port = 27015;
    saGNI.sin_family = AF_INET;
    saGNI.sin_addr.s_addr = sa.sin_addr.s_addr;
    saGNI.sin_port = htons(port);
    
    DWORD dwRetval = getnameinfo((struct sockaddr *) &saGNI,
        sizeof(struct sockaddr),
        hostname,
        NI_MAXHOST, servInfo, NI_MAXSERV, NI_NOFQDN);
    printf("HostName: %s", hostname);
    

    Note: I have changed the flag from NI_NUMERICSERV

    to

    NI_NOFQDN