#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MYPORT 3490	// porta de ligação para clientes
#define BACKLOG 10	// max ligações pendentes

int main(void) 
{
  int sockfd, new_fd;          // escuta em sockfd, novas ligações em new_fd
  struct sockaddr_in my_addr; // minha info de endereço
  struct sockaddr_in cl_addr; // info de endereço de clientes
  socklen_t sin_size;

  if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
    perror("socket");
    exit(1);
  }
  my_addr.sin_family = AF_INET;		// network byte order
  my_addr.sin_port = htons(MYPORT);	// converte de host byte order p/ net order
  my_addr.sin_addr.s_addr = INADDR_ANY; // det. automaticamente IP
  memset(&(my_addr.sin_zero), '\0', 8); // resto da struct a zero

  if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1) {
    perror("bind");
    exit(1);
  }
  if (listen(sockfd, BACKLOG) == -1) {
    perror("listen");
    exit(1);
  }
  while(1) {                   // ciclo de espera de ligações
    sin_size = sizeof(struct sockaddr_in);
    if ((new_fd= accept(sockfd,(struct sockaddr *)&cl_addr, &sin_size)) == -1) {
      perror("accept");
      continue;
    }
    printf("server: pedido de ligacao de %s\n",inet_ntoa(cl_addr.sin_addr));
    // inet_ntoa: conv ip host addr em string x.y.z.w

    if (!fork()) {     // processo filho para responder ao pedido
      close(sockfd);   // não precisa do listener
      if (send(new_fd, "Ola, mundo!\n", 14, 0) == -1) {
        perror("send"); 
        close(new_fd); exit(0);
      }
    }
    close(new_fd);  // pai já não precisa deste descriptor
    return 0;
  }
}
