chiark / gitweb /
[PATCH] added klibc version 0.82 (cvs tree) to the udev tree.
[elogind.git] / klibc / klibc / inet / bindresvport.c
1 /*
2  * inet/bindresvport.c
3  */
4
5 #include <errno.h>
6 #include <sys/types.h>
7 #include <sys/socket.h>
8 #include <netinet/in.h>
9 #include <string.h>
10 #include <unistd.h>
11
12 #define START_PORT      600
13 #define END_PORT        (IPPORT_RESERVED - 1)
14 #define NUM_PORTS       (END_PORT - START_PORT)
15
16 int bindresvport(int sd, struct sockaddr_in *sin)
17 {
18         struct sockaddr_in me;
19         static short port;
20         int ret = 0;
21         int i;
22
23         if (sin == NULL) {
24                 sin = &me;
25                 memset(sin, 0, sizeof(me));
26                 sin->sin_port = AF_INET;
27         }
28         else if (sin->sin_family != AF_INET) {
29                 errno = EPFNOSUPPORT;
30                 ret = -1;
31                 goto bail;
32         }
33         
34         if (port == 0) {
35                 port = START_PORT + (getpid() % NUM_PORTS);
36         }
37         
38         for (i = 0; i < NUM_PORTS; i++, port++) {
39                 sin->sin_port = htons(port);
40                 if ((ret = bind(sd, sin, sizeof(*sin))) != -1)
41                         break;
42                 if (port == END_PORT)
43                         port = START_PORT;
44         }
45
46  bail:
47         return ret;
48 }