]> sigrok.org Git - libserialport.git/blob - examples/list_ports.c
Release examples as public domain.
[libserialport.git] / examples / list_ports.c
1 #include <libserialport.h>
2 #include <stdio.h>
3
4 /* Example of how to get a list of serial ports on the system.
5  *
6  * This example file is released to the public domain. */
7
8 int main(int argc, char **argv)
9 {
10         /* A pointer to a null-terminated array of pointers to
11          * struct sp_port, which will contain the ports found.*/
12         struct sp_port **port_list;
13
14         printf("Getting port list.\n");
15
16         /* Call sp_list_ports() to get the ports. The port_list
17          * pointer will be updated to refer to the array created. */
18         enum sp_return result = sp_list_ports(&port_list);
19
20         if (result != SP_OK)
21         {
22                 printf("sp_list_ports() failed!\n");
23                 return -1;
24         }
25
26         /* Iterate through the ports. When port_list[i] is NULL
27          * this indicates the end of the list. */
28         int i;
29         for (i = 0; port_list[i] != NULL; i++)
30         {
31                 struct sp_port *port = port_list[i];
32
33                 /* Get the name of the port. */
34                 char *port_name = sp_get_port_name(port);
35
36                 printf("Found port: %s\n", port_name);
37         }
38
39         printf("Found %d ports.\n", i);
40
41         printf("Freeing port list.\n");
42
43         /* Free the array created by sp_list_ports(). */
44         sp_free_port_list(port_list);
45
46         /* Note that this will also free all the sp_port structures
47          * it points to. If you want to keep one of them (e.g. to
48          * use that port in the rest of your program), take a copy
49          * of it first using sp_copy_port(). */
50
51         return 0;
52 }