Getting listening ports and addresses programmatically

My problem: A program was using 127.0.0.2 (an alias for 127.0.0.1) to make a local connection on a specific port. However, one Windows 2003 server box was configured so that this port was being listened to on a specific network adapter (and hence a specific IP address). Hence, my local connection failed even though the port was open for listening.

Background: Type “netstat -p tcp -a -n” at the command prompt to get details of listening ports. The “Local Address” is adapter specific; “0.0.0.0” means it’s listening on all adapters (thus allowing connections to 127.0.0.1). In the case of this 2003 box, the port I wanted was specific to a particular IP address (adapter).

So, my program needed to connect to the adapter specific IP address and not 127.0.0.1. This is how to get the IP addresses and ports they’re listening on:


void DoItAgain()
{
   DWORD err;
   DWORD size = 0;
   // first get the size of the buffer required
   if((err=GetTcpTable (0,&size,FALSE))!=ERROR_INSUFFICIENT_BUFFER)
   {
      std::cerr << "Error " << err <<
         " getting tcp table size." << std::endl;
      return;
   }
   // next get the table
   std::vector buf(size);
   MIB_TCPTABLE *tbl = reinterpret_cast(&(*buf.begin()));
   if((err=GetTcpTable(tbl,&size,FALSE))!=NO_ERROR)
   {
      std::cerr << "Error " << err <<
         " getting tcp table." << std::endl;
      return;
   }
   // iterate through the entries
   for (DWORD dw = 0; dw < tbl->dwNumEntries; ++dw)
   {
      if(tbl->table[dw].dwState == MIB_TCP_STATE_LISTEN)
      {
         in_addr ad;
         ad.S_un.S_addr = tbl->table[dw].dwLocalAddr;
         std::cout << "Listening " << inet_ntoa(ad) <<
            ", port " << ntohs(tbl->table[dw].dwLocalPort) << std::endl;
      }
   }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s