How do I retrieve the IP of the system? India
  • 14 years ago

    Tell me the steps how to make and include lib file to MFC project so i can get the ip address of the system...if somebody can help me then tell me all this job i hav to do...from very starting..

    below is the code that i found ... that may be used for get the ip address of the system...


        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

        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());


        Ip = NULL;
        Ip = new char[17];
        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

        delete [] Ip;

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


Post a reply

No one has replied yet! Why not be the first?

Sign in or Join us (it's free).


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“A computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are, in short, a perfect match” - Bill Bryson