diff options
| author | Lennart Poettering <lennart@poettering.net> | 2007-04-18 20:22:27 +0000 | 
|---|---|---|
| committer | Lennart Poettering <lennart@poettering.net> | 2007-04-18 20:22:27 +0000 | 
| commit | 33f07017fb9f087d179da73e172a9d495de88e55 (patch) | |
| tree | ac5165a40121e0d442b17d28f52a3ea21df46f98 | |
| parent | a4ebf2e6c969b1ff4af0cab6be19856bf241c0c5 (diff) | |
add a simple example how to properly let the IP stack choose a free port number
git-svn-id: file:///home/lennart/svn/public/avahi/trunk@1438 941a03a8-eaeb-0310-b9a0-b1bbd8fe43fe
| -rw-r--r-- | docs/socket-auto-port.c | 48 | 
1 files changed, 48 insertions, 0 deletions
| diff --git a/docs/socket-auto-port.c b/docs/socket-auto-port.c new file mode 100644 index 0000000..850759a --- /dev/null +++ b/docs/socket-auto-port.c @@ -0,0 +1,48 @@ +#include <sys/socket.h> +#include <netinet/in.h> +#include <netinet/tcp.h> +#include <arpa/inet.h> +#include <inttypes.h> +#include <errno.h> +#include <stdio.h> + +int main(int argc, char *argv[]) { +    int s; +    struct sockaddr_storage sa; +    socklen_t salen; +    uint16_t port; +     +    if ((s = socket(PF_INET6, SOCK_STREAM, 0)) < 0) { +        if (errno == EAFNOSUPPORT) +            s = socket(PF_INET, SOCK_STREAM, 0); +     +        if (s < 0) { +            perror("socket()"); +            return 1; +        } +    } + +    if (listen(s, 2) < 0) { +        perror("listen()"); +        return 2; +    } + +    salen = sizeof(sa); +    if (getsockname(s, (struct sockaddr*) &sa, &salen) < 0) { +        perror("getsockname()"); +        return 3; +    } + +    if (((struct sockaddr*) &sa)->sa_family == AF_INET) +        port = ((struct sockaddr_in*) &sa)->sin_port; +    else +        port = ((struct sockaddr_in6*) &sa)->sin6_port; + +    printf("Selected port number %u\n", ntohs(port)); + +    /* ... hic sunt leones ... */ + +    sleep(60); +     +    return 0; +} | 
