// this is the simple server program to test out libipq; it accepts
// a connection, does a single receive, then closes the connection.
// Compile with:
// gcc -g -Wall server.c -o server

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define vf_fprintf(x) printf x

#define BUFSIZE 8000

int listenSocket(int listen_port)
{
  struct sockaddr_in a;
  int s,yes;

  if(listen_port<0){
    return -1;
  }

  s = socket(AF_INET, SOCK_STREAM, 0);
  if(s<0){
    fprintf(stderr,"Failed creating socket: %s",strerror(errno));
    return -1;
  }
  yes = 1;
  if(setsockopt(s, SOL_SOCKET, SO_REUSEADDR,(char *) &yes, sizeof (yes)) < 0){
    fprintf(stderr,"Failed setsockopt: %s",strerror(errno));
    close(s);
    return -1;
  }
  memset (&a, 0, sizeof (a));
  a.sin_port = htons (listen_port);
  a.sin_family = AF_INET;
  if(bind(s, (struct sockaddr *) &a, sizeof (a)) < 0) {
    fprintf(stderr,"Error binding to port %d: %s",listen_port,strerror(errno));
    close(s);
    return -1;
  }
  listen (s, 10);
  return s;
}

int main()
{
  int sock,conn_sock;
  unsigned int addrlen;
  struct sockaddr_in client_address;
  ssize_t bytes;
  char buf[BUFSIZE];
  long long counter;

  sock=listenSocket(8888);

  addrlen=sizeof(client_address);
  memset(&client_address,0,addrlen);

  counter=0;

  while(1){
    conn_sock=accept(sock,(struct sockaddr *)&client_address,&addrlen);

    memset(buf,0,BUFSIZE);
    bytes=recv(conn_sock,buf,BUFSIZE,0);
    if(bytes<0){
      fprintf(stderr,"Error: %s\n",strerror(errno));
    }
    else if(bytes==0){
      fprintf(stderr,"Did not receive any bytes\n");
    }
    else{
      if((counter%1000)==0){
	fprintf(stderr,"Message: %s\n",buf);
      }
      counter++;
    }

    close(conn_sock);

  }
  
  close(sock);

  return 0;
}
