/* server.c - code d'un serveur TCP */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

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

#define PORT  12345
#define QUEUE 10

static int nclients = 0;
/*
 * Syntax:    server [ port ]
 */
int main(int argc, char *argv[])
{
  struct protoent *ppe;
  struct sockaddr_in sin, sin2;
  int ss, sc, port, l;
  char buffer[1000];

  memset((char *)&sin,0,sizeof(sin));
  sin.sin_family = AF_INET;
  sin.sin_addr.s_addr = INADDR_ANY;

  if (argc > 1) { port = atoi(argv[1]); }
  else          { port = PORT;          }
  if (port <= 0) {
    fprintf(stderr,"server: numero de port incorrect.\n");
    exit(1);
  }
  sin.sin_port = htons((u_short)port);

  if ((ppe=getprotobyname("tcp"))==NULL) {
    perror("server getprotobyname(\"tcp\"): ");
    exit(1);
  }

  ;
  if ((ss=socket(PF_INET,SOCK_STREAM,ppe->p_proto)) < 0) {
    perror("server socket(): ");
    exit(1);
  }

  if (bind(ss, (struct sockaddr *)&sin,sizeof(sin)) < 0) {
    perror("server bind(): ");
    exit(1);
  }

  if (listen(ss, QUEUE) < 0) {
    perror("server listen(): ");
    exit(1);
  }

  /*
   * Allez on y va!
   * On accepte une connexion entrante et on traite le problème
   */

  while (1) {
    l = sizeof(sin2);
    if ( (sc=accept(ss,(struct sockaddr *)&sin2,&l)) < 0) {
      perror("server accept(): ");
      exit(1);
    }
    nclients++;
    sprintf(buffer,"Il y a eu %d client%s\n",nclients,nclients==1?".":"s.");
    send(sc,buffer,strlen(buffer),0);
    close(sc);
  }
}
