Getting listening ports and addresses programmatically

My problem: A program was using (an alias for 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; “” means it’s listening on all adapters (thus allowing connections to 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 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;
   // next get the table
   std::vector buf(size);
   MIB_TCPTABLE *tbl = reinterpret_cast(&(*buf.begin()));
      std::cerr << "Error " << err <<
         " getting tcp table." << std::endl;
   // 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;


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s