/*
  Example TCP server.
  Copyright (C) 2005 Russell Bradford

  This program is free software; you can redistribute it and/or
  modify it under the terms of the GNU General Public License
  as published by the Free Software Foundation; either version 2
  of the License, or (at your option) any later version.

  This program is distributed in the hope that it will be useful, 
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License (http://www.gnu.org/copyleft/gpl.html)
  for more details. 
*/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

#define PORT 12345
#define MESSAGE "hello"

int main(void)
{
  int sock, conn;
  socklen_t clilen;
  struct sockaddr_in server_addr, client_addr;

  /* create a STREAM (TCP) socket in the INET (IP) protocol */
  sock = socket(PF_INET, SOCK_STREAM, 0);

  if (sock < 0) {
    perror("creating socket");
    exit(1);
  }

  /* create server address: this will say where we will be willing to
     accept connections from */

  /* clear it out */
  memset(&server_addr, 0, sizeof(server_addr));

  /* it is an INET address */
  server_addr.sin_family = AF_INET;

  /* the client IP address, in network byte order */
  /* in this example we accept connections from ANYwhere */
  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);

  /* the port we are going to listen on, in network byte order */
  server_addr.sin_port = htons(PORT);

  /* associate the socket with the address and port */
  if (bind(sock, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
    perror("bind failed");
    exit(2);
  }

  /* start the socket listening for new connections */
  if (listen(sock, 5) < 0) {
    perror("listen failed");
    exit(3);
  }

  while (1) {

    /* now wait until we get a connection */
    printf("waiting for a connection...\n");
    clilen = sizeof(client_addr);
    conn = accept(sock, (struct sockaddr *)&client_addr, &clilen);

    if (conn < 0) {
      perror("accept failed");
      exit(4);
    }

    /* now client_addr contains the address of the client */
    printf("connection from %s\n", inet_ntoa(client_addr.sin_addr));

    printf("sending message\n");

    write(conn, MESSAGE, sizeof(MESSAGE));

    /* close connection */
    close(conn);
  }
  
  return 0;
}

