1 #include <sys/socket.h>
2 #include <netinet/in.h>
3 #include <netinet/tcp.h>
10 int main(int argc, char *argv[]) {
12 struct sockaddr_storage sa;
16 if ((s = socket(PF_INET6, SOCK_STREAM, 0)) < 0) {
17 if (errno == EAFNOSUPPORT)
18 s = socket(PF_INET, SOCK_STREAM, 0);
26 if (listen(s, 2) < 0) {
32 if (getsockname(s, (struct sockaddr*) &sa, &salen) < 0) {
33 perror("getsockname()");
37 if (((struct sockaddr*) &sa)->sa_family == AF_INET)
38 port = ((struct sockaddr_in*) &sa)->sin_port;
40 port = ((struct sockaddr_in6*) &sa)->sin6_port;
42 printf("Selected port number %u\n", ntohs(port));
44 /* ... hic sunt leones ... */