/* sockets.c

   Shane Eisenman - 11/2002

   This file contains generic TCP socket
   setup functions.  Functions here are 
   called by functions in chat.c
*/

/*--------------------------------------*/
#include "sockets.h"
#include "common.h"
/*--------------------------------------*/
void Open_Socket_As_Server(int *fd,int port) {

  struct sockaddr_in my_addr;   
  int yes=1;

  if ((*fd = socket(AF_INET, SOCK_STREAM, 0))==-1)
    Err_Exit("socket");

  if (setsockopt(*fd,SOL_SOCKET,SO_REUSEADDR,\
		 &yes,sizeof(int)) == -1)
    Err_Exit("setsockopt");

  my_addr.sin_family = AF_INET;        
  my_addr.sin_port = htons(port);    
  my_addr.sin_addr.s_addr = INADDR_ANY;
  memset(&(my_addr.sin_zero),'\0', 8);

  if (bind(*fd, (struct sockaddr *)&my_addr,\
	   sizeof(struct sockaddr)) == -1)
    Err_Exit("bind");

}
/*--------------------------------------*/
void Open_Socket_As_Client(int* fd,char* host,int port) {

  struct sockaddr_in server_addr;
  struct hostent* hostentity;

  if ((hostentity=gethostbyname(host)) == NULL)
    herror("gethostbyname");
  else {
    if ((*fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
      perror("socket");
    else {
      server_addr.sin_family = AF_INET;
      server_addr.sin_port = htons(port);
      server_addr.sin_addr = *((struct in_addr *)hostentity->h_addr);
      memset(&(server_addr.sin_zero), '\0', 8);
      
      if (connect(*fd, (struct sockaddr *)&server_addr,
		  sizeof(struct sockaddr)) == -1)
	perror("connect");
    }
  }
}
/*--------------------------------------*/
void Wait_For_Connect_Request(int fd) {

  if (listen(fd, BACKLOG) == -1)
    Err_Exit("listen");

}
/*--------------------------------------*/

