1 diff --git a/src/bindresvport.c b/src/bindresvport.c
2 index b197efa..bc75d29 100644
3 --- a/src/bindresvport.c
4 +++ b/src/bindresvport.c
5 @@ -62,6 +62,7 @@ bindresvport(sd, sin)
10 #define ENDPORT (IPPORT_RESERVED - 1)
11 #define NPORTS (ENDPORT - STARTPORT + 1)
13 @@ -76,10 +77,13 @@ bindresvport_sa(sd, sa)
15 struct sockaddr_in6 *sin6;
19 + static u_int16_t port;
20 + static short startport = STARTPORT;
23 + int nports = ENDPORT - startport + 1;
24 + int endport = ENDPORT;
28 salen = sizeof(myaddr);
29 @@ -119,13 +123,22 @@ bindresvport_sa(sd, sa)
33 - for (i = 0; i < NPORTS && res < 0 && errno == EADDRINUSE; i++) {
35 + for (i = 0; i < nports; ++i) {
36 *portp = htons(port++);
37 - if (port > ENDPORT) {
42 res = bind(sd, sa, salen);
43 + if (res >= 0 || errno != EADDRINUSE)
46 + if (i == nports && startport != LOWPORT) {
47 + startport = LOWPORT;
48 + endport = STARTPORT - 1;
49 + nports = STARTPORT - LOWPORT;
50 + port = LOWPORT + port % (STARTPORT - LOWPORT);