#include <stdio.h> 
#include <strings.h>
#include <stdlib.h> 
#include <errno.h> 
#include <string.h> 
#include <sys/types.h> 
#include <netinet/in.h> 
#include <sys/socket.h> 
#include <sys/wait.h> 
#include "server.h"

int open_server(int port)
{
  struct sockaddr_in my_addr;    /* my address information */
  int sockfd;
  char hostname[100];
  int n;

  // have server print out its name
  gethostname(hostname, 100);
  printf("hostname: %s\n", hostname);

  if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(1); 
  }

  if(setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (void *)&n , sizeof(int)) != 0) {
    fprintf(stderr, "Unable to set reuse address option\n");
  }

  
  my_addr.sin_family = AF_INET;         /* host byte order */
  my_addr.sin_port = htons(port);     /* short, network byte order */
  my_addr.sin_addr.s_addr = INADDR_ANY; /* auto-fill with my IP */
  bzero(&(my_addr.sin_zero), 8);        /* zero the rest of the struct */
  
  if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
    perror("bind");
    exit(1);
  }
  
  if (listen(sockfd, BACKLOG) == -1) {
    perror("listen");
    exit(1);
  }

  return sockfd;
}
