How to list serial ports in C?


This page explains how to scan serial ports using the Serialib library. Serialib is a cross-platform library written in C++.

The library has been tested on Windows and Linux. This project has been developed with Qt Creator and succesfully compile with:

Scanning ports

The best options to get the list of available serial ports is to open each device and check the status of the function openDevice:

// Test each port between COM1 and COM99 on Windows and between /dev/ttyS0 and /dev/ttyS99 on Linux
for (int i=1;i<99;i++)
    // Prepare the port name (Windows)
    #if defined (_WIN32) || defined( _WIN64)
        sprintf (device_name,"\\\\.\\COM%d",i);

    // Prepare the port name (Linux)
    #ifdef __linux__
        sprintf (device_name,"/dev/ttyACM%d",i-1);

    // try to connect to the device
    if (device.openDevice(device_name,115200)==1)
        printf ("Device detected on %s\n", device_name);
        // Close the device before testing the next port

See also

Last update : 05/23/2022