1 /* This file has be substantially modified from the original OpenBSD source */
3 /* $OpenBSD: bindresvport.c,v 1.17 2005/12/21 01:40:22 millert Exp $ */
6 * Copyright 1996, Jason Downs. All rights reserved.
7 * Copyright 1998, Theo de Raadt. All rights reserved.
8 * Copyright 2000, Damien Miller. All rights reserved.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
31 /* OPENBSD ORIGINAL: lib/libc/rpc/bindresvport.c */
35 #ifndef HAVE_BINDRESVPORT_SA
36 #include <sys/types.h>
37 #include <sys/socket.h>
39 #include <netinet/in.h>
40 #include <arpa/inet.h>
46 #define ENDPORT (IPPORT_RESERVED - 1)
47 #define NPORTS (ENDPORT - STARTPORT + 1)
50 * Bind a socket to a privileged IP port
53 bindresvport_sa(int sd, struct sockaddr *sa)
56 struct sockaddr_storage myaddr;
57 struct sockaddr_in *in;
58 struct sockaddr_in6 *in6;
65 memset(&myaddr, 0, sizeof(myaddr));
66 sa = (struct sockaddr *)&myaddr;
67 salen = sizeof(myaddr);
69 if (getsockname(sd, sa, &salen) == -1)
70 return -1; /* errno is correctly set */
73 memset(&myaddr, 0, salen);
78 in = (struct sockaddr_in *)sa;
79 salen = sizeof(struct sockaddr_in);
80 portp = &in->sin_port;
81 } else if (af == AF_INET6) {
82 in6 = (struct sockaddr_in6 *)sa;
83 salen = sizeof(struct sockaddr_in6);
84 portp = &in6->sin6_port;
93 port = arc4random_uniform(NPORTS) + STARTPORT;
98 for(i = 0; i < NPORTS; i++) {
101 error = bind(sd, sa, salen);
103 /* Terminate on success */
107 /* Terminate on errors, except "address already in use" */
108 if ((error < 0) && !((errno == EADDRINUSE) || (errno == EINVAL)))
119 #endif /* HAVE_BINDRESVPORT_SA */