How to Detect Available COM Ports

I’ve seen this question many times asked in forums. Unfortunatelly, not all the answers are ok. A a good wait to find the available COM ports is by using function GetDefaultCommConfig, that returns the default configuration for a specified communication device. Following code shows how to use it:

#include <vector>
#include <string> 

// this can be defined in a separate file
#ifdef _UNICODE
  #define tstring std::wstring
#else
  #define tstring std::string
#endif   

void DetectComPorts(std::vector< tstring >& ports, size_t upperLimit = 128)
{
  for(size_t i=1; i<=upperLimit; i++)
  {
	TCHAR strPort[32] = {0};
	_stprintf(strPort, _T("\\\\.\\COM%d"), i);   

	DWORD dwSize = 0;
	LPCOMMCONFIG lpCC = (LPCOMMCONFIG) new BYTE[1];
	BOOL ret = GetDefaultCommConfig(strPort, lpCC, &dwSize);
	delete [] lpCC;	   

	lpCC = (LPCOMMCONFIG) new BYTE[dwSize];
	ret = GetDefaultCommConfig(strPort, lpCC, &dwSize);
	delete [] lpCC;   

	if(ret) ports.push_back(strPort);
  }
}

Here is an example of how to use this function:

int _tmain(int argc, _TCHAR* argv[])
{
  std::vector< tstring > ports;
  DetectComPorts(ports);   

  for(std::vector< tstring >::const_iterator it = ports.begin(); it != ports.end(); ++it)
  {
	std::cout << *it << std::endl;
  }   

  return 0;
}

1 thought on “How to Detect Available COM Ports”

  1. For me, I had to take away the “\\\\.\\” and it still works with high COM port numbers. Furthermore, the port seems to exist whenever dwSize is not zero, so I skip the second call. Here is my code for Open Watcom c compiler in Windows XP:

    void printAvailableComPorts(void)
    {
    int i;
    char comStr[] = “COM345”; // Not “\\\\.\\COM345”
    Bool foundPorts = 0;
    uint32 dwSize = 0;
    unsigned char lpccArray[1] = {0};
    LPCOMMCONFIG lpCC;
    lpCC = (LPCOMMCONFIG) lpccArray;
    printf(“\nDetecting available COM ports:”);
    for (i = 0; i <= 255; i++)
    {
    itoa(i, &comStr[3], 10);
    dwSize = 0;
    GetDefaultCommConfig(comStr, lpCC, &dwSize);
    if (dwSize != 0)
    {
    if (foundPorts) printf(", %d", i);
    else printf(" %d", i);
    foundPorts = 1;
    }
    }
    if (foundPorts) printf(".\n");
    else printf(" None!\n");
    fflush(stdout);
    }

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.