 /*
 * socket.c
 *
 *  Created on: Apr 25, 2012
 *      Author: xw795
 */
#include <sys/stat.h>
#include <sys/mman.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <rtai.h>
#include <rtai_lxrt.h>
#include <semaphore.h>

#define MSG_SIZE 3			// message size


void error(const char *msg);

int main(int argc, char *argv[])
{
	int sock;
	int boolval = 1;			// for a socket option
	int fd1;
	struct sockaddr_in addr;
	unsigned int length;
	char input;
	char code[3];
	int check;
	int sign=0;

   if (argc != 2)
   {
	   printf("usage: %s port\n", argv[0]);
       exit(1);
   }

   fd1 = open("/dev/rtf/0",O_RDWR);


   sock = socket(AF_INET, SOCK_DGRAM, 0); // Creates socket. Connectionless.
   if (sock < 0)
	   error("socket");

   if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &boolval, sizeof(boolval)) < 0)  // change socket permissions to allow broadcast
     	{
     		printf("error setting socket options\n");
     		exit(-1);
     	}

   addr.sin_family = AF_INET;
   addr.sin_port = htons(atoi(argv[1]));
   addr.sin_addr.s_addr = inet_addr("10.3.52.255");	// broadcast address

   length = sizeof(struct sockaddr_in);		// size of structure

   sock = socket(AF_INET, SOCK_DGRAM, 0); // Creates socket. Connectionless.
   	   if (sock < 0)
   		   error("socket");


   	   if (setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &boolval, sizeof(boolval)) < 0)  // change socket permissions to allow broadcast
   	    {
       		printf("error setting socket options\n");
    		exit(-1);
       	}

   	  addr.sin_family = AF_INET;
      addr.sin_port = htons(atoi(argv[1]));
  	  addr.sin_addr.s_addr = inet_addr("10.3.52.255");	// broadcast address

  	   length = sizeof(struct sockaddr_in);		// size of structure

  	   while(1)
  	   {
			check=read(fd1,&input,sizeof(input));			
			if(check > 0)
			{
				if(strncmp(input,'T',1)==0)
				{
					sendto(sock, input, strlen(input), 0,(const struct sockaddr *)&addr,length);
					printf("Input the Password: ");
				}
				else
				{
					strncat(code,&input,1);
//					printf("code = %s",code);
					sign++;
					if(sign == 3)
					{
						sendto(sock, code, strlen(code), 0,(const struct sockaddr *)&addr,length);
					}
				}
			}	
		}

   return 0;
}


void error(const char *msg)
{
    perror(msg);
    exit(0);
}
