]> git.meshlink.io Git - catta/blob - docs/socket-auto-port.c
Fix compilation error caused by ACX_THREAD
[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 #include <unistd.h>
9
10 int main(int argc, char *argv[]) {
11     int s;
12     struct sockaddr_storage sa;
13     socklen_t salen;
14     uint16_t port;
15
16     if ((s = socket(PF_INET6, SOCK_STREAM, 0)) < 0) {
17         if (errno == EAFNOSUPPORT)
18             s = socket(PF_INET, SOCK_STREAM, 0);
19
20         if (s < 0) {
21             perror("socket()");
22             return 1;
23         }
24     }
25
26     if (listen(s, 2) < 0) {
27         perror("listen()");
28         return 2;
29     }
30
31     salen = sizeof(sa);
32     if (getsockname(s, (struct sockaddr*) &sa, &salen) < 0) {
33         perror("getsockname()");
34         return 3;
35     }
36
37     if (((struct sockaddr*) &sa)->sa_family == AF_INET)
38         port = ((struct sockaddr_in*) &sa)->sin_port;
39     else
40         port = ((struct sockaddr_in6*) &sa)->sin6_port;
41
42     printf("Selected port number %u\n", ntohs(port));
43
44     /* ... hic sunt leones ... */
45
46     sleep(60);
47
48     return 0;
49 }