Obtain all IP addresses of local machine



Click here for larger image

Environment: Compiled on: Visual Studio .NET & Windows XP Pro. Code works on any Windows machine.

You're obviously writing TCP/IP applications. You have the ability to create sockets and bind them to specific ports. You may bind to all the ports, you may bind to 127.0.0.1, or finally you may want to bind to specific IP addresses of your local machine.

If you do NOT wish to bind to all ports because then you can't have other applications serving off the same machine. You may want bind to a specific IP address of your local machine, then you'd need to find out how to obtain all the IP addresses located on your machine.

Attached is the code required to simply start up winsock in a Windows environment, and enumerate all the IP addresses on your local machine. It is a console application, no MFC, not much Windows specific code.

It has been tested in a Windows XP Professional environment, along with a Windows 2000 Server environment. We enumarate all the IPs until the list terminates (with a NULL pointer). It should have no problems working with Windows 95/98/Me/2k/XP/CE.

I also tested it in our server environment where we have 32 IP addresses and we have software listening on the same port on different IPs, all located on the one NIC card that has access to the internet. In fact we are hosting listening servers on port 80 along side IIS. This requires you to disable socket pooling, but that is another story.

If you have any questions, don't hesitate to e-mail me.

#include <stdio.h>
#include <WinSock.h>
#pragma comment(lib, "wsock32.lib")

int main(int argc, char *argv[])
{
 WORD wVersionRequested;
 WSADATA wsaData;
 char name[255];
 PHOSTENT hostinfo;
 wVersionRequested = MAKEWORD( 1, 1 );
 char *ip;

 if ( WSAStartup( wVersionRequested, &wsaData ) == 0 )
  if( gethostname ( name, sizeof(name)) == 0)
  {
   printf("Host name: %s\n", name);

   if((hostinfo = gethostbyname(name)) != NULL)
   {
    int nCount = 0;
    while(hostinfo->h_addr_list[nCount])
    {
     ip = inet_ntoa(*(
          struct in_addr *)hostinfo->h_addr_list[nCount]);

     printf("IP #%d: %s\n", ++nCount, ip);
    }
   }
  }
 return 0;
}

Downloads

Download demo project - 28.0 Kb
Download source - 28.0 Kb


Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date