Ip address of a computer using winsock

    There is a function gethostbyname for getting the ip address using Winsock. This function will retrieve the ip address details into a variable of type “structure hostent”. 

    The first step in creating this program is to ensure the socket library is initialized, if it is not initialized else-where. The next step is to call the gethostbyname function which will return a pointer to the hostent structure. This pointer to the hostent structure can be used to get the ip address into a sockaddr_in type.
    In fact it is possible to get the ip without using the sockaddr_in structure also. But using sockaddr_in is a much cleaner way of doing the work.

 

    Please feel free to copy/paste the function below and use/manipulate it in your applications wherever needed.


#include <winsock2.h> 

void GetHostIP()
{
    char *Ip;
    WSADATA wsaData;
    struct hostent *pHostEnt; 
    struct sockaddr_in tmpSockAddr; //placeholder for the ip address

    // Not needed if it is already taken care by some other part of the application
    WSAStartup(MAKEWORD(2,0),&wsaData); 

    char hostname[25];
    strcpy(hostname,”Test Computer Name”)
    //This will retrieve the ip details and put it into pHostEnt structure
    pHostEnt = gethostbyname(hostname);

    if(pHostEnt == NULL)
    {
        printf(“Error occured: %sn”,GetLastError());
        return;
    }

    memcpy(&tmpSockAddr.sin_addr,pHostEnt->h_addr,pHostEnt->h_length);

    Ip = NULL;
    Ip = new char[17];
    strcpy(Ip,inet_ntoa(tmpSockAddr.sin_addr));
    printf(“Ip Address of the machine %s is %sn”,Ip);

    // Not needed if it is already taken care by some other part of the application
    WSACleanup();
    delete [] Ip;
}


Note:
The socket programs in MFC need the library ws2_32.lib to be referenced before linking. Otherwise the VC++ linker throws errors.