/*
 * --- GSMP-COPYRIGHT-NOTE-BEGIN ---
 * 
 * This copyright note is auto-generated by ./scripts/Create-CopyPatch.
 * Please add additional copyright information _after_ the line containing
 * the GSMP-COPYRIGHT-NOTE-END tag. Otherwise it might get removed by
 * the ./scripts/Create-CopyPatch script. Do not edit this copyright text!
 * 
 * GSMP: voip/src/UdpServer.cc
 * General Sound Manipulation Program is Copyright (C) 2000 - 2004
 *   Valentin Ziegler and René Rebe
 * 
 * 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; version 2. A copy of the GNU General
 * Public License can be found in the file LICENSE.
 * 
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANT-
 * ABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 * 
 * --- GSMP-COPYRIGHT-NOTE-END ---
 */

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h> /* close() */
#include <string.h> /* memset() */

#include <iostream>

#define LOCAL_SERVER_PORT 6666
#define MAX_MSG 100

int main (int argc, char *argv[]) {
  
  int sd, rc, n;
  socklen_t cliLen;
  struct sockaddr_in cliAddr, servAddr;
  char msg[MAX_MSG];

  /* socket creation */
  sd=socket (AF_INET, SOCK_DGRAM, 0);
  if (sd < 0) {
    std::cerr << "cannot open socket" << std::endl;
    return(1);
  }

  /* bind local server port */
  servAddr.sin_family = AF_INET;
  servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servAddr.sin_port = htons(LOCAL_SERVER_PORT);
  rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
  if (rc < 0) {
    std::cerr << "cannot bind port number " << LOCAL_SERVER_PORT << std::endl;
    return(1);
  }

  /* server infinite loop */
  while (true) {
    
    /* init buffer */
    memset(msg, 0x0, MAX_MSG);
    
    std::cerr << "waiting for data on port UDP "
	      << LOCAL_SERVER_PORT << std::endl;
    
    /* receive message */
    cliLen = sizeof(cliAddr);
    n = recvfrom (sd, msg, MAX_MSG, 0, (struct sockaddr *) &cliAddr, &cliLen); 
    if (n < 0) {
      std::cerr << "cannot receive data" << std::endl;
      continue;
    }
    
    /* print received message */
    std::cerr << "from: " << inet_ntoa (cliAddr.sin_addr)
	      << ":" << ntohs (cliAddr.sin_port)
              << " " << msg << std::endl;
    
    /* send message */
    std::cerr << "sending data back"
	      << std::endl;

    rc = sendto(sd, msg, strlen (msg)+1, 0, 
		(struct sockaddr*) &cliAddr,
		sizeof (cliAddr));
    
    if (rc < 0) {
      std::cerr << "cannot send data back" << std::endl;
      close (sd);
      return (1);
    }
    
  }/* end of server infinite loop */

  return 0;
}
