]> git.meshlink.io Git - catta/blob - docs/socket-auto-port.c
add a simple example how to properly let the IP stack choose a free port number
[catta] / docs / socket-auto-port.c
1 #include <sys/socket.h>
2 #include <netinet/in.h>
3 #include <netinet/tcp.h>
4 #include <arpa/inet.h>
5 #include <inttypes.h>
6 #include <errno.h>
7 #include <stdio.h>
8
9 int main(int argc, char *argv[]) {
10     int s;
11     struct sockaddr_storage sa;
12     socklen_t salen;
13     uint16_t port;
14     
15     if ((s = socket(PF_INET6, SOCK_STREAM, 0)) < 0) {
16         if (errno == EAFNOSUPPORT)
17             s = socket(PF_INET, SOCK_STREAM, 0);
18     
19         if (s < 0) {
20             perror("socket()");
21             return 1;
22         }
23     }
24
25     if (listen(s, 2) < 0) {
26         perror("listen()");
27         return 2;
28     }
29
30     salen = sizeof(sa);
31     if (getsockname(s, (struct sockaddr*) &sa, &salen) < 0) {
32         perror("getsockname()");
33         return 3;
34     }
35
36     if (((struct sockaddr*) &sa)->sa_family == AF_INET)
37         port = ((struct sockaddr_in*) &sa)->sin_port;
38     else
39         port = ((struct sockaddr_in6*) &sa)->sin6_port;
40
41     printf("Selected port number %u\n", ntohs(port));
42
43     /* ... hic sunt leones ... */
44
45     sleep(60);
46     
47     return 0;
48 }