home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-386-Vol-2of3.iso / x / xhearts.zip / CONNECT.C < prev    next >
C/C++ Source or Header  |  1992-01-07  |  1KB  |  54 lines

  1. /*
  2.  * connect.c
  3.  *
  4.  * client connection to hearts server
  5.  */
  6.  
  7. #include <stdio.h>
  8. #include "defs.h"
  9. #include "local.h"
  10.  
  11. char *getenv();
  12.  
  13. /*
  14.  * Make connection to host running the hearts distributor server,
  15.  * return fd of new socket.
  16.  */
  17. connect_to(servhost, port)
  18. char    *servhost;            /* name of host running server */
  19. int    port;
  20. {
  21.     int    sock;
  22.     struct    hostent *host;
  23.     struct    servent *distributor;
  24.     struct    sockaddr_in sockaddr;
  25.     char    buf[64];
  26.  
  27.     if ((host = gethostbyname(servhost)) == NULL)  {
  28.         perror("gethostbyname");
  29.         exit(1);
  30.     }
  31.     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)  {
  32.         perror("socket");
  33.         exit(1);
  34.     }
  35.     bzero((char *) &sockaddr, sizeof (sockaddr));
  36.     bcopy(host->h_addr, (char *) &sockaddr.sin_addr, host->h_length);
  37.     sockaddr.sin_family = AF_INET;
  38.     if (port)
  39.         sockaddr.sin_port = htons(port);
  40.     else {
  41.         if ((distributor = getservbyname(SERVICE, PROTO)) == NULL)  {
  42.             (void) sprintf(buf, "%s: service not found\n", SERVICE);
  43.             fputs(buf, stderr);
  44.             exit(1);
  45.         }
  46.         sockaddr.sin_port = distributor->s_port;
  47.     }
  48.     if (connect(sock, (struct sockaddr *) &sockaddr, sizeof(sockaddr)) < 0) {
  49.         (void) close (sock);
  50.         return(0);
  51.     }
  52.     return(sock);
  53. }
  54.