#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>

#include <stdio.h>
#include <string.h>

#include "clnt_conn.h"

int clnt_conn(char *host, unsigned short port) {
  struct  hostent  *ptrh;    /* pointer to a host table entry       */
  struct  sockaddr_in sad;   /* structure to hold an IP address     */
  int     sd;                /* socket descriptor                   */

  memset((char *)&sad,0,sizeof(sad));  /* clear sockaddr structure */
  sad.sin_family = AF_INET;            /* set family to Internet     */
  sad.sin_port = htons(port) ;

  /* Convert host name to equivalent IP address and copy to sad. */
  ptrh = gethostbyname(host) ;
  if ( ((char *)ptrh) == NULL )
    return(-1) ;	/* unable to look up host */
  memcpy(&sad.sin_addr, ptrh->h_addr, ptrh->h_length);

  /* Create a socket. */
  sd = socket(PF_INET, SOCK_STREAM, 0);
  if (sd < 0)
    return(-1) ;	/* extremely unlikely */

  /* Connect the socket to the specified server. */
  if (connect(sd, (struct sockaddr *)&sad, sizeof(sad)) < 0)
    return(-1) ;

  return(sd) ;
}
