2 * Copyright (c) 2010, Oracle America, Inc.
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above
11 * copyright notice, this list of conditions and the following
12 * disclaimer in the documentation and/or other materials
13 * provided with the distribution.
14 * * Neither the name of the "Oracle America, Inc." nor the names of its
15 * contributors may be used to endorse or promote products derived
16 * from this software without specific prior written permission.
18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
21 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
22 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
23 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
25 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
27 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35 #include <sys/types.h>
36 #include <sys/socket.h>
37 #include <netinet/in.h>
38 #include <libc-lock.h>
41 * Locks the static variables in this file.
43 __libc_lock_define_initialized (static, lock
);
46 * Bind a socket to a privileged IP port
49 bindresvport (int sd
, struct sockaddr_in
*sin
)
52 struct sockaddr_in myaddr
;
57 #define ENDPORT (IPPORT_RESERVED - 1)
58 #define NPORTS (ENDPORT - STARTPORT + 1)
59 static short startport
= STARTPORT
;
61 if (sin
== (struct sockaddr_in
*) 0)
64 memset (sin
, 0, sizeof (*sin
));
65 sin
->sin_family
= AF_INET
;
67 else if (sin
->sin_family
!= AF_INET
)
69 __set_errno (EAFNOSUPPORT
);
75 port
= (__getpid () % NPORTS
) + STARTPORT
;
78 /* Initialize to make gcc happy. */
81 int nports
= ENDPORT
- startport
+ 1;
82 int endport
= ENDPORT
;
84 __libc_lock_lock (lock
);
87 for (i
= 0; i
< nports
; ++i
)
89 sin
->sin_port
= htons (port
++);
92 res
= __bind (sd
, sin
, sizeof (struct sockaddr_in
));
93 if (res
>= 0 || errno
!= EADDRINUSE
)
97 if (i
== nports
&& startport
!= LOWPORT
)
100 endport
= STARTPORT
- 1;
101 nports
= STARTPORT
- LOWPORT
;
102 port
= LOWPORT
+ port
% (STARTPORT
- LOWPORT
);
106 __libc_lock_unlock (lock
);
110 libc_hidden_def (bindresvport
)