#include "socket_functions.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

  int 
  make_socket (unsigned short int port)
  {
    int sock;
    struct sockaddr_in name;

    /* Create the socket. */
    sock = socket (PF_INET, SOCK_STREAM, 0);
    if (sock < 0)
      {
        perror ("socket");
        exit (EXIT_FAILURE);
      }

    /* Give the socket a name. */
    name.sin_family = AF_INET;
    name.sin_port = htons (port);
    name.sin_addr.s_addr = htonl (INADDR_ANY);
    /*
     * Set up to reuse server addresses automatically and bind to the
     * specified port.
     * Look in CreateSocket in tclUnixChan.c from tcl source
     * If this is not present when server closes before client, the next
     * time server starts -> bind: Address in use 
     */
    
   int status = 1;
   (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &status,
                     sizeof(status));
   if (status == -1) {
       perror ("reuse");
   }
   
    if (bind (sock, (struct sockaddr *) &name, sizeof (name)) < 0)
      {
        perror ("bind");
        exit (EXIT_FAILURE);
      }

    return sock;
  }

  void 
  init_sockaddr (struct sockaddr_in *name,
                 const char *hostname,
                 unsigned short int port)
  {
    struct hostent *hostinfo;

    name->sin_family = AF_INET;
    name->sin_port = htons (port);
    hostinfo = gethostbyname (hostname);
    if (hostinfo == NULL) 
      {
        fprintf (stderr, "Unknown host %s.\n", hostname);
        exit (EXIT_FAILURE);
      }
    name->sin_addr = *(struct in_addr *) hostinfo->h_addr;
  }

int prepare_socket( int sock )
{
    /*
     * Set up to reuse server addresses automatically and bind to the
     * specified port.
     * Look in CreateSocket in tclUnixChan.c from tcl source
     * If this is not present when server closes before client, the next
     * time server starts -> bind: Address in use 
     */
    
    int status = 1;
   (void) setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *) &status,
                     sizeof(status));
   if (status == -1) {
       perror ("reuse");
   }
   return status;
}
