home *** CD-ROM | disk | FTP | other *** search
/ Gold Fish 3 / goldfish_volume_3.bin / files / comm / tcp / amitcp-sdk / src / rpclib / bindresvport.c < prev    next >
Encoding:
C/C++ Source or Header  |  1994-09-29  |  1.3 KB  |  58 lines

  1. /*
  2.  *      $Id: bindresvport.c,v 4.2 1994/09/29 23:48:50 jraja Exp $
  3.  *
  4.  *      Copyright © 1994 AmiTCP/IP Group,
  5.  *                       Network Solutions Development Inc.
  6.  *                       All rights reserved. 
  7.  */
  8.  
  9. /*static  char sccsid[] = "@(#)bindresvport.c    2.2 88/07/29 4.0 RPCSRC 1.8 88/02/08 SMI";*/
  10.  
  11. /*
  12.  * Copyright (c) 1987 by Sun Microsystems, Inc.
  13.  */
  14.  
  15. #include <sys/param.h>
  16. #include <sys/types.h>
  17. #include <sys/socket.h>
  18. #include <netinet/in.h>
  19. #include <errno.h>
  20.  
  21. /*
  22.  * Bind a socket to a privileged IP port
  23.  */
  24. bindresvport(int sd, struct sockaddr_in *sin)
  25. {
  26.     int res;
  27.     static short port;
  28.     struct sockaddr_in myaddr;
  29.     int i;
  30.  
  31. #define STARTPORT 600
  32. #define ENDPORT (IPPORT_RESERVED - 1)
  33. #define NPORTS    (ENDPORT - STARTPORT + 1)
  34.  
  35.     if (sin == (struct sockaddr_in *)0) {
  36.         sin = &myaddr;
  37.         bzero(sin, sizeof (*sin));
  38.         sin->sin_family = AF_INET;
  39.     } else if (sin->sin_family != AF_INET) {
  40.         errno = EPFNOSUPPORT;
  41.         return (-1);
  42.     }
  43.     if (port == 0) {
  44.         port = ((u_short)getpid() % NPORTS) + STARTPORT;
  45.     }
  46.     res = -1;
  47.     errno = EADDRINUSE;
  48.     for (i = 0; i < NPORTS && res < 0 && errno == EADDRINUSE; i++) {
  49.         sin->sin_port = htons(port++);
  50.         if (port > ENDPORT) {
  51.             port = STARTPORT;
  52.         }
  53.         res = bind(sd,
  54.             (struct sockaddr *)sin, sizeof(struct sockaddr_in));
  55.     }
  56.     return (res);
  57. }
  58.