Ip address of a computer using winsock ������������������������������������������������������������������������������������������������������������

CoderSource.net
Ip address of a computer using winsock
Rating:

Date: 5/1/2004 12:00:00 AM

    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: %s\n",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 %s\n",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.

You Can Rate this Article, if you are Logged In      
 

More Links from CoderSource.net:

 
Refer to a Friend:

Your Details:

Name:     e-mail:

Friend Details:

Name:    e-mail:    


MENU
Home
MFC 
C++
.Net
WIN32
Programming
Forum
My Articles
Add to Google
Add to My Yahoo!
Welcome to Community Server Login | Register | Faq  

SEARCH
Google
 

NOTES:


Thanks for visiting our CoderSource.net. This site will be improved with more articles. Interested visitors can also submit their articles through the Submit Article link.Your article will also be published after due consideration by the editor. 

© Copyright 2003. All rights on content reserved by CoderSource.net. Contact    About Us