Back to index

glibc  2.9
Defines | Functions
bindrsvprt.c File Reference
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

Go to the source code of this file.

Defines

#define STARTPORT   600
#define LOWPORT   512
#define ENDPORT   (IPPORT_RESERVED - 1)
#define NPORTS   (ENDPORT - STARTPORT + 1)

Functions

int bindresvport (int sd, struct sockaddr_in *sin)

Define Documentation

#define ENDPORT   (IPPORT_RESERVED - 1)
#define LOWPORT   512
#define NPORTS   (ENDPORT - STARTPORT + 1)
#define STARTPORT   600

Function Documentation

int bindresvport ( int  sd,
struct sockaddr_in sin 
)

Definition at line 44 of file bindrsvprt.c.

{
  static short port;
  struct sockaddr_in myaddr;
  int i;

#define STARTPORT 600
#define LOWPORT 512
#define ENDPORT (IPPORT_RESERVED - 1)
#define NPORTS       (ENDPORT - STARTPORT + 1)
  static short startport = STARTPORT;

  if (sin == (struct sockaddr_in *) 0)
    {
      sin = &myaddr;
      __bzero (sin, sizeof (*sin));
      sin->sin_family = AF_INET;
    }
  else if (sin->sin_family != AF_INET)
    {
      __set_errno (EAFNOSUPPORT);
      return -1;
    }

  if (port == 0)
    {
      port = (__getpid () % NPORTS) + STARTPORT;
    }

  /* Initialize to make gcc happy.  */
  int res = -1;

  int nports = ENDPORT - startport + 1;
  int endport = ENDPORT;
 again:
  for (i = 0; i < nports; ++i)
    {
      sin->sin_port = htons (port++);
      if (port > endport)
       port = startport;
      res = __bind (sd, sin, sizeof (struct sockaddr_in));
      if (res >= 0 || errno != EADDRINUSE)
       break;
    }

  if (i == nports && startport != LOWPORT)
    {
      startport = LOWPORT;
      endport = STARTPORT - 1;
      nports = STARTPORT - LOWPORT;
      port = LOWPORT + port % (STARTPORT - LOWPORT);
      goto again;
    }

  return res;
}

Here is the call graph for this function:

Here is the caller graph for this function: