title: How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?
body: <p>What is the proper way to get a list of all available serial ports/devices on a Linux system?</p>
  
  <p>In other words, when I iterate over all devices in <code>/dev/</code>, how do I tell which ones are serial ports in the classic way, that is, those usually supporting baud rates and <a href="http://en.wikipedia.org/wiki/RS-232#RTS.2FCTS_handshaking" rel="noreferrer">RTS/CTS</a> flow control?</p>
  
  <p>The solution would be coded in C.</p>
  
  <p>I ask because I am using a third-party library that does this clearly wrong: It appears to only iterate over <code>/dev/ttyS*</code>. The problem is that there are, for instance, serial ports over USB (provided by USB-RS232 adapters), and those are listed under /dev/ttyUSB*. And reading the <a href="http://www.linux.org/docs/ldp/howto/Serial-HOWTO.html" rel="noreferrer">Serial-HOWTO at Linux.org</a>, I get the idea that there'll be other name spaces as well, as time comes.</p>
  
  <p>So I need to find the official way to detect serial devices. The problem is that none appears to be documented, or I can't find it.</p>
  
  <p>I imagine one way would be to open all files from <code>/dev/tty*</code> and call a specific <code>ioctl()</code> on them that is only available on serial devices. Would that be a good solution, though?</p>
  
  <h3>Update</h3>
  
  <p><em>hrickards</em> suggested to look at the source for "setserial".
  Its code does exactly what I had in mind:</p>
  
  <p>First, it opens a device with:</p>
  
  <pre><code>fd = open (path, O_RDWR | O_NONBLOCK)
  </code></pre>
  
  <p>Then it invokes:</p>
  
  <pre><code>ioctl (fd, TIOCGSERIAL, &amp;serinfo)
  </code></pre>
  
  <p>If that call returns no error, then it's a serial device, apparently.</p>
  
  <p>I found similar code in <em><a href="http://en.wikibooks.org/wiki/Serial_Programming:Unix/termios" rel="noreferrer">Serial Programming/termios</a></em>, which suggested to also add the <code>O_NOCTTY</code> option.</p>
  
  <p><strong>There is one problem with this approach, though:</strong></p>
  
  <p>When I tested this code on BSD Unix (that is, Mac&nbsp;OS&nbsp;X), it worked as well. <strong><em>However</em></strong>, serial devices that are provided through Bluetooth cause the system (driver) to try to connect to the Bluetooth device, which takes a while before it'll return with a timeout error. This is caused by just opening the device. And I can imagine that similar things can happen on Linux as well - ideally, I should not need to open the device to figure out its type. I wonder if there's also a way to invoke <code>ioctl</code> functions without an open, or open a device in a way that it does not cause connections to be made?</p>
  
  <p>What should I do?</p>