int main(int argc, char *argv[] ) {
	char line[100];
	const char *file = argv[1];
	const char *output_file = argv[2];
 
	int num_ips = count_ips(file);
	char ip_array[num_ips][sizeof line];
   
	FILE *fp = fopen(file,"r");
	
	int i;
	for (i = 0; i < num_ips; i++) {
		fgets(line, sizeof line, fp);
		strcpy(ip_array[i], line);
	}
	fclose(fp);
	
	hostname_to_ip("www.msn.com", host_to_ip);
		
	for (i = 0; i < num_ips; i++) {
		test_proxy(ip_array[i], output_file, atoi(argv[3]));
	}

	return 0;
}
void main(int argc, char **argv)
{
    char uri[MAX_STR_LEN];
    char hostname[MAX_STR_LEN];
    char identifier[MAX_STR_LEN]="";
    char ip[100];
    int sockid, port;
    //printf("Open URI: ");
    //scanf("%s", uri);
    //printf("Testing Begin...n");

    //test for parse
    if(parse_URI(argv[1], hostname, &port, identifier) == 0)
    {
        printf("Errorr in Parasingn ");
        exit(1);
    }
    
    //get the ip address
    if(hostname_to_ip(hostname, ip))
    {
        printf("Error resolving: %s\n", hostname);
        exit(1);
    }
    printf("port----->%d\n",port);

    // gernerate socket id
    sockid = open_connection(hostname, port, ip, identifier);

    // send and receive message
    perform_http(sockid, identifier, hostname);
}
int tcp_connect(char* serverName, int serverPort)
{
  int sockfd;
  struct sockaddr_in serv_addr;
  memset(&serv_addr, '0', sizeof(serv_addr));

  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if(sockfd < 0)
  {
    printf("\n Error : Could not create socket \n");
    //exit(1);
    return -1;
  }

  serv_addr.sin_family = AF_INET;
  serv_addr.sin_port = htons(serverPort);
  
  char serverIP[100];
  hostname_to_ip(serverName, serverIP);
  if(inet_pton(AF_INET, serverIP, &serv_addr.sin_addr)<=0)
  {
    printf("\n inet_pton error occured\n");
    //exit(1);
    return -1;
  }

  if( connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
  {
    printf("\n Error : Connect Failed \n");
    //exit(1);
    return -1;
  }

  return sockfd;
}
Exemple #4
0
int connect_to_server(char * hostname, int port) {
  int socket_id, e;

  // create socket
  socket_id = socket(AF_INET, SOCK_STREAM, 0);

  struct in_addr *addr;
  e = hostname_to_ip(hostname, &addr);
  printf("%s\n", inet_ntoa(*addr));

  // bind to port/address
  struct sockaddr_in sock = {
    .sin_family = AF_INET,
    .sin_port = htons(port),
    .sin_addr = *addr
  };

  bind(socket_id, (struct sockaddr *)&sock, sizeof(sock));

  // attempt a connection
  e = connect(socket_id, (struct sockaddr*)&sock, sizeof(sock));
  if (e < 0) return e;

  return socket_id;
}
Exemple #5
0
void *run_notification_client(void* ptr) {
	char* server_host = (char*)ptr;
	char server_ip[100];
	struct sockaddr_in server_addr;
	char buf[48];
	int lan_server_port;
	struct conn_info tmp_conn_info;
	pthread_t tmp_trans_thread;
	pthread_t heart_beat_thread;

	while (1) {
		if (hostname_to_ip(server_host, server_ip)) {
			printf("Server hostname %s not resolved.\n", server_host);
			exit(EXIT_FAILURE);
		}
		printf("Server IP: %s\n", server_ip);
		server_addr.sin_family = AF_INET;
		inet_aton(server_ip, &(server_addr.sin_addr));
		server_addr.sin_port = htons(SERVER_PUSH_NOTIFICATION_PORT);
		int notification_socket = socket(AF_INET, SOCK_STREAM, 0);
		while(connect(notification_socket, (struct sockaddr*)&server_addr, sizeof(server_addr))<0) {
			printf("Connection failed. Retrying...\n");
			sleep(1);
		}
		printf("Server connected.\n");
		pthread_create(&heart_beat_thread, NULL, run_heart_beat_client, (void*)&notification_socket);
		pthread_detach(heart_beat_thread);
		while(1) {
			memset(buf, '\0', 48);
			int bytes_read = recv(notification_socket, buf, 48, 0);
			if (bytes_read<=0) {
				printf("Notification connection lost. Re-connecting.\n");
				close(notification_socket);
				break;
			}

			conn_count++;
			printf("Connection count=%d\n", conn_count);
			
			printf("New connection. buf=%s\n", buf);
			char* devider = strstr(buf, "|");
			char* recognize_code = (char*)malloc(32);
			memset(recognize_code, '\0', 32);
			memcpy(recognize_code, buf, devider-buf);
			char* lan_server_ip = (char*)malloc(32);
			sscanf(devider+1, "%d|%s", &lan_server_port, lan_server_ip);
			tmp_conn_info.lan_server_ip = lan_server_ip;
			tmp_conn_info.lan_server_port = lan_server_port;
			tmp_conn_info.recognize_code = recognize_code;
			tmp_conn_info.server_ip = server_ip;
			tmp_conn_info.server_port = SERVER_TRANSACT_PORT;

			pthread_create(&tmp_trans_thread, NULL, run_transaction, (void*)&tmp_conn_info);
			pthread_detach(tmp_trans_thread);

		}
	}
	return NULL;
}
Exemple #6
0
void		ft_ping(char **av)
{
	char				ip[100];

	if (ft_isalpha(av[1][0]))
		hostname_to_ip(av[1] , ip);
	send_to_socket(ip);
}
Exemple #7
0
int whatthe_query(char *server , char *query , char **response)
{
	char ip[32] , message[100] , buffer[1500];
	int sock , read_size , total_size = 0;
	struct sockaddr_in dest;
    
	sock = socket(AF_INET , SOCK_STREAM , IPPROTO_TCP);
    
    //Prepare connection structures :)
    memset( &dest , 0 , sizeof(dest) );
    dest.sin_family = AF_INET;
    
	printf("\nResolving %s..." , server);
	if(hostname_to_ip(server , ip))
	{
		printf("Failed");
		return 1;
	}
	printf("%s" , ip);    
	dest.sin_addr.s_addr = inet_addr( ip );
	dest.sin_port = htons( 43 );
    
	//Now connect to remote server
	if(connect( sock , (const struct sockaddr*) &dest , sizeof(dest) ) < 0)
	{
		perror("connect failed");
	}
	
	//Now send some data or message
	printf("\nQuerying for ... %s ..." , query);
	sprintf(message , "%s\r\n" , query);
	if( send(sock , message , strlen(message) , 0) < 0)
	{
		perror("send failed");
	}
	
	//Now receive the response
	while( (read_size = recv(sock , buffer , sizeof(buffer) , 0) ) )
	{
		*response = realloc(*response , read_size + total_size);
		if(*response == NULL)
		{
			printf("realloc failed");
		}
		memcpy(*response + total_size , buffer , read_size);
		total_size += read_size;
	}
	printf("Done");
	fflush(stdout);
	
	*response = realloc(*response , total_size + 1);
	*(*response + total_size) = '\0';
	
	close(sock);
	return 0;
}
Exemple #8
0
int informDirectoryServerMaybeAbsent(){
	// Initialize variables
	int sock;
	struct sockaddr_in server;

	// Create socket
	sock = socket(AF_INET , SOCK_STREAM , 0);
	if (sock == -1)
	{
		puts("Could not create socket");
		return -1;
	}
	puts("Socket created");

	//Connect to Directory Register and get ip and port for service
	char iptemp[100];
	hostname_to_ip(ServerDirectoryIP, iptemp);
		
	server.sin_addr.s_addr = inet_addr(iptemp);
	server.sin_family = AF_INET;
	server.sin_port = htons(ServerDirectoryPort);

	//Connect to Directory Service
	puts("Trying to connect to Directory Service");
	int connected = 1;
	while(connected == 1){
		connected = connect(sock , (struct sockaddr *)&server , sizeof(server));
	}

	if(connected == 0){
		//Connected to Directory Service
		puts("Connected");
	}else{
		puts("Server Directory Connection failed");
		return -1;
	}

	//Let Directory know you are the client
	if(sendInt(sock, 0) < 0){
		puts("Send connector type client failed");
		close(sock);
		return -1;
	}

	// Tell the directory there is problem connecting to the server
	if(sendInt(sock, 0) < 1){
		puts("Send connector type client failed");
		close(sock);
		return -1;
	}

	//Close connection to Directory Service
	close(sock);
	return 1;
}
int main(int argc , char *argv[])
{
	if(argc <2)
	{
		printf("usage : command domain-address\n");
		exit(1);
	}
	
	char *hostname = argv[1];
	char ip[100];
	
	hostname_to_ip(hostname , ip);
	printf("%s resolved to %s" , hostname , ip);
	
	printf("\n");
	
}
int HTTPHandler::sendGetRequest(String url)
{
    std::string ip;
    String request;
    String host;

#if 0
    /* get the host and url */
    if(url.contains("/"))
    {
        host = url.before("/");
        url = url.after("/");
    }
    else
    {
        host = url;
        url = "";
    }

    if(!url.empty())
    {
    request = "GET " + url + " HTTP 1.0\r\n";
    request += "Host: " + host + "\r\n\r\n";
    }
    else
    {
    }
#else
    if(url.contains("/"))
    {
        host = url.before("/");
    }
    else
    {
        host = url;
    }
    request = "GET http://" + url + " HTTP/1.0\r\n\r\n";
#endif

    /* get the ip addr */
    hostname_to_ip(host,ip);

    mpSocket = new Socket(ip,80);
    return mpSocket->write(request);
}
HTTPHandler::HTTPHandler(String url):mpSocket(NULL),mUrl(url)
{
    std::string ip;
    String request;
    String host;

    if(mUrl.contains("/"))
    {
        host = mUrl.before("/");
    }
    else
    {
        host = mUrl;
    }
    hostname_to_ip(host,ip);

    mpSocket = new Socket(ip,80);
}
int getServerFromDirectory(int *ip, int *port){

		//Initialize variables
		int sockd, result;
		struct sockaddr_in serverDirectory;

		//Create socket
		sockd = socket(AF_INET , SOCK_STREAM , 0);
	    if (sockd == -1)
	    {
	        puts("Could not create socket");
			return -1;
	    }
	    puts("Socket created");

		//Connect to Directory Register and get ip and port for service
		char addressFromHost[100];
	
		hostname_to_ip(ServerDirectoryIP, addressFromHost);
	
	    serverDirectory.sin_family = AF_INET;
	    serverDirectory.sin_addr.s_addr = inet_addr(addressFromHost);
	    serverDirectory.sin_port = htons(ServerDirectoryPort);

		//Connect to Directory Service
		puts("Trying to connect to Directory Service");

		while (connect(sockd, (struct sockaddr *)&serverDirectory, sizeof(serverDirectory)) < 0) {
			// Here is my error
			printf("Error when connecting! %s\n",strerror(errno));

			// Try Again
			sockd = socket(AF_INET , SOCK_STREAM , 0);
			if (sockd == -1)
			{
				puts("Could not create socket");
				return -1;
			}
			puts("Socket created");
		}


		//Connected to Directory Service
	    puts("Connected");

		//Let Directory know you are the worker directory
		if(sendInt(sockd, 0) < 0){
			puts("Send connector type worker directory failed");
			close(sockd);
			return -1;
		}

		// Tell the directory there the reason for connecting
		if(sendInt(sockd, 1) < 1){
			puts("Send connector reason worker directory failed");
			close(sockd);
			return -1;
		}

		//Get Status of Server Found or Not
		if(readInt(sockd, &result) < 0){
			puts("Receive Query Result failed");
			close(sockd);
			return -1;
		}else{
			if(result == 0){
				puts("Server Not Found");
				close(sockd);
				return -1;
			}
		}

		printf("Got Result = %d\n",result);

		//Get IP
		if(recv(sockd , ip , sizeof(int)*4,0) < 0){
			puts("Receive IP failed");
			close(sockd);
			return -1;
		}

		//Send the ACK
		if(sendAck(sockd) < 0){
			puts("Send ACK failed");
			close(sockd);
			return -1;
		}

		//Get Port
		if(readInt(sockd , port) < 0){
			puts("Receive Port failed");
			close(sockd);
			return -1;
		}

		//Successful
		//Close connection to Directory Service
		close(sockd);
		return 1;
}
/**
 * void run(int argc, char **argv)
 * 
 * Starts the server, processes command line arguments, initiates all necessary
 * functions and threads and enters infinite loop accepting user input.
 */
void run(int argc, char **argv) {
    char user_input_buffer[250];
    char addr_buffer[INET_ADDRSTRLEN] = {0};
    char *buff;
    struct in_addr tmp_addr;
    int port;
    int tmp_num;
    
    /* Get start timestamp */
    gettimeofday(&ts_start, NULL);
    
    /* Init logger first */
    if(argc >= 4) {
        init_logger(argv[3]);
    }
    else {
        init_logger(STRINGIFY(DEFAULT_LOGFILE));
    }
    
    /* Validate input */
    if(argc >= 3) {
        
        /* Validate ip address */
        if(inet_pton(AF_INET, argv[1], (void *) &tmp_addr) <= 0 &&
                !hostname_to_ip(argv[1], addr_buffer)) {
            
            help();
            raise_error("Error validating server adress.\n");
            
        }
        
        if(!addr_buffer[0]) {
            strcpy(addr_buffer, argv[1]);
        }
        
        /* Validate port */
        port = (int) strtoul(argv[2], NULL, 10);
        
        if(port <= 0 || port >= 65536) {
            help();
            raise_error("Port number is out of range.\n");
        }
        
        if(port <= 1024 && port != 0) {
            log_line("Trying to bind to a port number lower than 1024, this "
                    "might required administrator privileges.", LOG_ALWAYS);
        }
        
        /* Got log severity */
        if(argc >= 5) {
            log_level = (int) strtol(argv[4], NULL, 10);
        }
        
        sprintf(log_buffer,
                "Setting logging level to %d",
                log_level
                );
        
        log_line(log_buffer, LOG_ALWAYS);
        
        /* Got verbose */
        if(argc == 6) {
            verbose_level = (int) strtol(argv[5], NULL, 10);
        }
        
        sprintf(log_buffer,
                "Setting verbose level to %d",
                verbose_level
                );
        
        log_line(log_buffer, LOG_ALWAYS);
    }
    else {
        help();
        raise_error("Invalid arguments.\n");
    }
    
    /* Initiate server */
    init_server(addr_buffer, port);
    
    /* Start watchdog */
    pthread_mutex_init(&mtx_thr_watchdog, NULL);
    pthread_mutex_lock(&mtx_thr_watchdog);
    
    if(pthread_create(&thr_watchdog, NULL, start_watchdog, (void *) &mtx_thr_watchdog) != 0) {
        raise_error("Error starting watchdog thread.");
    }
    
    /* Start receiver */
    pthread_mutex_init(&mtx_thr_receiver, NULL);
    pthread_mutex_lock(&mtx_thr_receiver);
    
    if(pthread_create(&thr_receiver, NULL, start_receiving, (void *) &mtx_thr_receiver) != 0) {
        raise_error("Error starting receiving thread.");
    }
    
    /* Start sender */
    pthread_mutex_init(&mtx_thr_sender, NULL);
    pthread_mutex_lock(&mtx_thr_sender);
    
    if(pthread_create(&thr_sender, NULL, start_sending, (void *) &mtx_thr_sender) != 0) {
        raise_error("Error starting sender thread.");
    }
    
    /* Initiate server command line loop */
    while(1) {
        printf("CMD: ");
        
        if(fgets(user_input_buffer, 250, stdin) != NULL) {
            /* Exit server with exit, shutdown, halt or close commands */
            if( (strncmp(user_input_buffer, "exit", 4) == 0) ||
                    (strncmp(user_input_buffer, "shutdown", 8) == 0) ||
                    (strncmp(user_input_buffer, "halt", 4) == 0) ||
                    (strncmp(user_input_buffer, "close", 5) == 0)) {
                
                _shutdown();
                
                break;                
            }
            
            /* Set number that will be rolled */
            else if (strncmp(user_input_buffer, "force_roll", 10) == 0) {
                /* Strip header */
                if(strtok(user_input_buffer, " ") != NULL) {
                    buff = strtok(NULL, " ");
                    
                    if(buff != NULL) {
                        /* Get number */
                        force_roll = (int) strtoul(buff, NULL, 10);

                        if(force_roll >= 1 && force_roll <= 6) {
                            sprintf(log_buffer,
                                    "CMD: Forcing roll on all consequent rolls to %d",
                                    force_roll
                                    );
                            
                            log_line(log_buffer, LOG_ALWAYS);
                        }
                        else {
                            log_line("CMD: Rolling will be random now.", LOG_ALWAYS);
                        }
                    }
                }
            }
            
            /* Set log level */
            else if(strncmp(user_input_buffer, "set_log", 7) == 0) {
                if(strtok(user_input_buffer, " ") != NULL) {
                    buff = strtok(NULL, " ");
                    
                    if(buff) {
                        tmp_num = (int) strtoul(buff, NULL, 10);
                        
                        if(tmp_num >= LOG_NONE || tmp_num <= LOG_ALWAYS) {
                            log_level = tmp_num;
                            
                            sprintf(log_buffer,
                                    "CMD: Setting log level to %d",
                                    log_level
                                    );
                            
                            log_line(log_buffer, LOG_ALWAYS);
                        }
                    }
                }
            }
            
            /* Set log level */
            else if(strncmp(user_input_buffer, "set_verbose", 11) == 0) {
                if(strtok(user_input_buffer, " ") != NULL) {
                    buff = strtok(NULL, " ");
                    
                    if(buff) {
                        tmp_num = (int) strtoul(buff, NULL, 10);
                        
                        if(tmp_num >= LOG_NONE || tmp_num <= LOG_ALWAYS) {
                            verbose_level = tmp_num;
                            
                            sprintf(log_buffer,
                                    "CMD: Setting verbose level to %d",
                                    verbose_level
                                    );
                            
                            log_line(log_buffer, LOG_ALWAYS);
                        }
                    }
                }
            }
            
            /* Get server uptime */
            else if(strncmp(user_input_buffer, "uptime", 6) == 0) {
                display_uptime();
            }
            
            /* Get current number of clients (event timeouted) */
            else if(strncmp(user_input_buffer, "playercount", 11) == 0) {
                sprintf(log_buffer,
                        "Current number of clients (including timeouted) is %d",
                        client_num
                        );
                
                log_line(log_buffer, LOG_ALWAYS);
            }

	    /* Force sound on to all clients */
	    else if(strncmp(user_input_buffer, "sound_on", 8) == 0) {
		broadcast_clients("FORCE_SOUND;1", 1);

		strcpy(log_buffer, "Forcing sound ON to all clients!");

		log_line(log_buffer, LOG_ALWAYS);
	    }
	    
	    /* Force sound off to all clients */
	    else if(strncmp(user_input_buffer, "sound_off", 9) == 0) {
		broadcast_clients("FORCE_SOUND;0", 1);

		strcpy(log_buffer, "Forcing sound ON to all clients!");

		log_line(log_buffer, LOG_ALWAYS);
	    }
        }
    }
}
Exemple #14
0
  main(int argc,char *argv[])
  
{
    int i,j,k,n,q,len; 
    pid_t pid;
    char startTime[4][26], endTime[4][26];
    FILE *lfp;
    char filname[100]; //log filename
    char filnm[100];   // filenames with different sizes
    char hstname[100];   
    long int milsecS, milsecE;
    double delay, swp, totalDelay=0, avgDelay;
    char delayS[30];
    int itr=4; //Iterator for looping each file collection
    hstname[99]='\0';
    endTime[0][26]='\0';
    endTime[1][26]='\0';
    endTime[2][26]='\0';
    endTime[3][26]='\0';
    startTime[0][26]='\0';
    startTime[1][26]='\0';
    startTime[2][26]='\0';
    startTime[3][26]='\0';
	time_t timers, timere;
    struct tm *tm_infos, *tm_infoe;
    char mesg[1000];
    double dlay[itr][3];
   

    for(i=1;i<=5;i++)
    {
     totalDelay=0;
     avgDelay=0;
     if(i==1)
     strcpy(filnm, "file32B.txt");
     else if(i==2)
     strcpy(filnm, "file1KB.txt");
     else if(i==3)
     strcpy(filnm, "file256KB.txt");
     else if(i==4)
     strcpy(filnm, "file512KB.txt");
     else if(i==5)
     strcpy(filnm, "file1MB.txt");
     //printf("\n");
     //printf("Filename is: %s\n", filnm);
     len=strlen(filnm)+1;

   /* GETTING CURRENT HOSTNAME */ 
    gethostname(hstname, 99);

    /* CREATING LOG MESSAGES */
    /*resetting mesg*/
    strcpy(mesg, "");
    strcat(mesg, argv[1]);
    strcat(mesg, ",");
    strcat(mesg, hstname);
    strcat(mesg, ",");
    strcat(mesg,filnm);
    strcat(mesg, ",");
   
    /* START TIME */ 
    struct timeval tvBegin, tvEnd;
    struct timeval *tvB, *tvE;

    for(j=0;j<itr;j++)
    { 
    
    //strcat(mesg, "\n Start time: ");
    //strcat(mesg, buffer); 
    //printf("%s\n", mesg);
  
    /* CREATING FILE NAME DYNAMICALLY */ 
    strcpy(filname, "RTT_log_");
    strcat(filname, hstname);
    strcat(filname, ".log");
    int sockid, newsockid,i,getfile,ack,msg,msg_2,c;
    int no_writen,start_xfer, num_blks,num_last_blk;
    struct sockaddr_in my_addr, server_addr; 
    FILE *fp; 
    char in_buf[MAXSIZE];
    char ip[100];
    if(argc != 2) {
	printf("error: usage : sftp hostname \n"); 
	exit(0);
	}
    no_writen = 0;
    num_blks = 0;
    num_last_blk = 0;
    //len = strlen(argv[2])+1;
    //printf("File name is: %s\n", argv[2]);
    //printf("Hostname is: %s\n", argv[1]);
    //printf("client: creating socket\n");
  long int schDelay=ntohl(schDelay);
   //printf("client: starting to get file contents\n");
    gettimeofday(&tvBegin, NULL);
    tvB=&tvBegin;
    milsecS=(tvB->tv_sec)*1000000L-tvB->tv_usec;
   // printf("Start in milliseconds: %ld\n", milsecS);
    //dlay[j][0]=(float)milsecS;
    //time_t timers, timere;
    //struct tm *tm_infos, *tm_infoe;
    time(&timers);
    tm_infos = localtime(&timers);
   strftime(startTime[j], 26, "%Y%m%d%H%M%S", tm_infos);
	//strcat(mesg, startTime[j]);
	//strcat(mesg, ",");
    dlay[j][0]=atof(startTime[j]);  //Recording first start time
   // printf("Start time of %d transfer:%s\n", j, startTime[j]);
    if ((sockid = socket(AF_INET,SOCK_STREAM,0)) < 0)
      { printf("client: socket error : %d\n", errno); exit(0);
          }
  
    //printf("client: binding my local socket\n");
    bzero((char *) &my_addr,sizeof(my_addr));
    my_addr.sin_family = AF_INET;
    my_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    my_addr.sin_port = htons(CLIENT_PORT_ID);
    if (bind(sockid ,(struct sockaddr *) &my_addr,sizeof(my_addr)) < 0)
           {printf("client: bind  error :%d\n", errno);
           
    }
                                             
    //printf("client: starting connect\n");
    bzero((char *) &server_addr,sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    char *hostname=argv[1];
    hostname_to_ip(hostname , ip);
    //printf("IP is: %s\n", ip);
    server_addr.sin_addr.s_addr = inet_addr(ip);
   // printf("address is:%s\n", server_addr.sin_addr.s_addr);
    server_addr.sin_port = htons(SERVER_PORT_ID);
     if (connect(sockid ,(struct sockaddr *) &server_addr,
                                             sizeof(server_addr)) < 0)
           {printf("client: connect  error :%d\n", errno); exit(0);
           }


  /* Once we are here, we've got a connection to the server */

    /* tell server that we want to get a file */
    getfile = htons(REQUESTFILE);
    //printf("client: sending command request to ftp server\n");
    if((writen(sockid,(char *)&getfile,sizeof(getfile))) < 0)
       {printf("client: write  error :%d\n", errno); exit(0);} 

    /* want for go-ahead from server */
    msg = 0;  
    if((readn(sockid,(char *)&msg,sizeof(msg)))< 0)
       {printf("client: read  error :%d\n", errno); exit(0); }
    msg = ntohs(msg);   
    if (msg==COMMANDNOTSUPPORTED) {
	 printf("client: server refused command. goodbye\n");
         exit(0);
         }
     //  else
      //   printf("client: server replied %d, command supported\n",msg);
    

    /* send file name to server */
    //printf("client: sending filename\n");
       //if ((writen(sockid,argv[2],len))< 0)
       if ((writen(sockid,filnm,len))< 0)
         {printf("client: write  error :%d\n", errno); exit(0);}
    /* see if server replied that file name is OK */
    msg_2 = 0;
    if ((readn(sockid,(char *)&msg_2,sizeof(msg_2)))< 0)
        {printf("client: read  error :%d\n", errno); exit(0); }   
    msg_2 = ntohs(msg_2);
    if (msg_2 == BADFILENAME) {
       printf("client: server reported bad file name. goodbye.\n");
       exit(0);
       }
    // else
     //    printf("client: server replied %d, filename OK\n",msg_2);


    //printf("client: sending start transfer command\n");
    start_xfer = STARTTRANSFER;
    start_xfer = htons(start_xfer);
    if ((writen(sockid,(char *)&start_xfer,sizeof(start_xfer)))< 0)
           {printf("client: write  error :%d\n", errno); exit(0);
           }
    //if ((fp = fopen(argv[2],"w")) == NULL)
    if ((fp = fopen(filnm,"w")) == NULL)
        {printf(" client: local open file error \n");exit(0);}
            
    

     if((readn(sockid,(char *)&num_blks,sizeof(num_blks))) < 0)
             {printf("client: read error on nblocks :%d\n",errno);exit(0);}
     num_blks = ntohs(num_blks);
     //printf("client: server responded: %d blocks in file\n",num_blks);
     ack = ACK;  
     ack = htons(ack);
     if((writen(sockid,(char *)&ack,sizeof(ack))) < 0)
        {printf("client: ack write error :%d\n",errno);exit(0);
        }

   
     if((readn(sockid,(char *)&num_last_blk,sizeof(num_last_blk))) < 0)
             {printf("client: read error :%d on nbytes\n",errno);exit(0);}
     num_last_blk = ntohs(num_last_blk);  
     //printf("client: server responded: %d bytes last blk\n",num_last_blk);
     if((writen(sockid,(char *)&ack,sizeof(ack))) < 0)
        {printf("client: ack write error :%d\n",errno);exit(0);
        }


  /* BEGIN READING BLOCKS BEING SENT BY SERVER */
    for(i= 0; i < num_blks; i ++) {
      if((readn(sockid,in_buf,MAXSIZE)) < 0)
	  {printf("client: block error read: %d\n",errno);exit(0);}
      no_writen = fwrite(in_buf,sizeof(char),MAXSIZE,fp);
      if (no_writen == 0) {printf("client: file write error\n");exit(0);}
      if (no_writen != MAXSIZE) 
         {printf("client: file write  error : no_writen is less\n");exit(0);}
      /* send an ACK for this block */
      if((writen(sockid,(char *)&ack,sizeof(ack))) < 0)
         {printf("client: ack write  error :%d\n",errno);exit(0);}
     // printf(" %d...",i);
      }


/*IF THERE IS A LAST PARTIALLY FILLED BLOCK, READ IT */

    if (num_last_blk > 0) {
        //printf("%d\n",num_blks);      
        if((readn(sockid,in_buf,num_last_blk)) < 0)
           {printf("client: last block error read :%d\n",errno);exit(0);}
        no_writen = fwrite(in_buf,sizeof(char),num_last_blk,fp); 
        if (no_writen == 0) 
          {printf("client: last block file write err :%d\n",errno);exit(0);}
        if (no_writen != num_last_blk) 
        {printf("client: file write error : no_writen is less 2\n");exit(0);}
        if((writen(sockid,(char *)&ack,sizeof(ack))) < 0)
	         {printf("client :ack write  error  :%d\n",errno);exit(0);}
        }
      //else printf("\n");
      

  /*FILE TRANSFER ENDS. CLIENT TERMINATES AFTER  CLOSING ALL ITS FILES
    AND SOCKETS*/ 
    
   // strftime(buffer, 26, "%Y/%m/%d %H:%M:%S", tm_infoe);
    //strcat(mesg, "\n End time: ");
    //strcat(mesg, ",");
    //strcat(mesg, buffer);
    gettimeofday(&tvEnd, NULL);
    tvE=&tvEnd;
    milsecE=(tvE->tv_sec)*1000000L-tvE->tv_usec;
	time(&timere);
    tm_infoe = localtime(&timere);
    //printf("End time in milliseconds: %ld\n", milsecE);
    //dlay[j][1]=(float)milsecE;
	strftime(endTime[j], 26, "%Y%m%d%H%M%S", tm_infoe);
    //strcat(mesg, endTime[j]);
	//strcat(mesg, ",");
   // sscanf(endTime[j], "%f", &dlay[j][1]);
    dlay[j][1]=atof(endTime[j]);
    //printf("End time of %d transfer:%s\n", j, endTime[j]);
    fclose(fp);
    //printf("client: FILE TRANSFER COMPLETE\n");
    close(sockid);
    
    delay=fabs((milsecE-milsecS)/1000);
    //printf("Without fabs Delay is: %ld\n",(milsecE-milsecS)/1000); 
    //printf("Delay is: %f\n", delay);
    dlay[j][2]=delay;
    }

    for(k=0;k<itr-1;k++)
    {
      for(n=0;n<itr-k-1;n++)
      {
        if(dlay[n][2]>dlay[n+1][2])
	{
	  for(q=0;q<3;q++)
	  {
	  swp = dlay[n][q];
	  dlay[n][q]=dlay[n+1][q];
	  dlay[n+1][q]=swp;
	  }
	}
       }
     }

/*    for (k=0;k<itr-1;k++)
    {
        for (n=0;n<itr-k-1;n++)
        {
            if (dlay[n] > dlay[n+1])
            {
                swp =  dlay[n];
                dlay[n] = dlay[n+1];
                dlay[n+1] = swp;
            }
        }
    }*/
    for(q=0;q<3;q++)
    {
    for(k=0;k<itr-1;k++)
    {
    snprintf(delayS, 30, "%.0f", dlay[k][q]);
    strcat(mesg, delayS);
    strcat(mesg, ",");
     // printf("%lf\n",dlay[k][q]);
    }
    }
    totalDelay=dlay[0][2]+dlay[1][2]+dlay[2][2]; 
    //printf("Total delay is: %f\n", totalDelay);
    avgDelay=totalDelay/3;
    //printf("Average delay is: %f\n", avgDelay);
    snprintf(delayS, 30, "%.0f", avgDelay);
    //strcat(mesg, "\n Delay is: ");
    strcat(mesg, delayS);
    strcat(mesg, "\n"); 
    
    printf("%s\n", mesg);

   /* WRITING STATISTICS TO LOG FILE*/
    lfp=fopen(filname, "a");
    fputs(mesg, lfp);
    fclose(lfp); 
}
}
Exemple #15
0
int main(int argc , char *argv[])
{
    int sock;
    struct sockaddr_in server;
    char message[1000] , server_reply[2000];
    
    if(argc != 4)
    {
    	printf("Incorrect Command Line Args!\nPlease use format: <node> ");
    	printf("<NodeIPAddr> <RepIPAddr> <Port>\n");
    	exit(1);
    	
    }
    printf("Node:\n\tConnecting to IPAddr: %s\n\tPort: %s\n",argv[2],argv[3]);
    char* getIPAddr;
    char* getIPAddr2;
    struct hostent* host = gethostbyname(argv[1]);
    char** current_addr = host->h_addr_list;
    struct in_addr* addr = (struct in_addr*)(*current_addr); 
    getIPAddr = inet_ntoa(*addr); 
    
    /* Convert user input to ip address */   
    char *hostname = argv[1];
    char ip[100];
     
    hostname_to_ip(hostname , ip);
    printf("%s resolved to %s" , hostname , ip);
     
    printf("\n");
    
    
    char *hostname2 = argv[2];
    char ip2[100];
     
    hostname_to_ip(hostname2 , ip2);
    printf("%s resolved to %s" , hostname2 , ip2);
     
    printf("\n");
    
    /* Format hostent info for repeater */
    struct hostent* host2 = gethostbyname(argv[2]);
    char** current_addr2 = host2->h_addr_list;
    struct in_addr* addr2 = (struct in_addr*)(*current_addr2); 
    getIPAddr2 = inet_ntoa(*addr2); 

    /*Create socket to connect to repeater */
    sock = socket(AF_INET , SOCK_STREAM , 0);
    if (sock == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");
    
    server.sin_addr.s_addr = inet_addr(argv[2]);
    server.sin_family = AF_INET;
    server.sin_port=htons(atoi(argv[3]));
    server.sin_addr.s_addr=*(long*)host2->h_addr_list[0]; /* set the addr */
 	
    /*Make connection to server */
    if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        perror("connect failed. Error");
        return 1;
    }
     
    puts("Connected\n");
    //keep communicating with server
    char messageType[2];
    struct Frame* myFrame = NULL;
    char message_data[1024];
    char data_dest[1024];
    char msgType[2];
    char trainingMsg2[2];
    char trainingMsg3[2];
    char trainingMsg4[1024];
    int recvMsgSize;
    char* base = malloc(sizeof(char)*100);
    int msgType_int;
    int atoi_msg_type;
    char ip_t[100];
    char ip_t2[100];
    while(1)
    {
        //user options
    	printf("Enter message type: \n");
    	printf("\t1 for request normal\n");
    	printf("\t2 for request high\n");
    	printf("\t4 for data packet\n");
    	printf("\t11 for training message\n");
        scanf("%s" , messageType);
        atoi_msg_type = atoi(messageType);
        int four = 4;
        
        strcpy(ip_t,ip);
        strcpy(ip_t2,ip2);
        if(  atoi_msg_type == 4 )
        {
        	printf("Enter hostname of who you want to send to: \n");
        	scanf("%s",data_dest);
        	hostname_to_ip(data_dest,ip_t);
        	printf("Enter message data: \n");
        	scanf("%s",message_data);
        	myFrame = createFrame(messageType,ip_t,ip_t2,message_data);

        }
        else
        {
        	myFrame = createFrame(messageType,ip_t,ip_t2,"");
        }

    	if(sendFrame(sock,myFrame) == 0)
    		printf("send successful\n");
    	
         
      		
		if((recvMsgSize=recv(sock,msgType,2,0))<0)
		{
			perror("recv() failed");
			exit(1);
		}
		if((recvMsgSize=recv(sock,trainingMsg2,2,0))<0)
		{
			perror("recv() failed");
			exit(1);
		}
        
		int a = trainingMsg2[0];
		int b = trainingMsg2[1];
		
		
		
		if((recvMsgSize=recv(sock,trainingMsg3,2,0))<0)
		{
			perror("recv() failed");
			exit(1);
		}
		int c = trainingMsg3[0];
		int d = trainingMsg3[1];
		
		if((recvMsgSize=recv(sock,trainingMsg4,1024,0))<0)
		{
			perror("recv() failed");
			exit(1);
		}	
		
		sprintf(base,"169.235.%d.%d",c,d);
		printf("%s\n\n",base);
		
		msgType_int = atoi(msgType);
		
		char hostname[1024];

		char ip[100];

		unsigned char* token;

		unsigned char* token2;
		unsigned char* token3;
		
		int dadd1;
		int dadd2;
		
		switch(msgType_int)
		{
			case 0: printf("You received an Idle Down Frame\n");
			break;
			case 3: printf("You received a grant Frame\n");
			break;
			case 4: printf("Data received from repeater\n");

				gethostname(hostname,1014);
				hostname_to_ip(hostname,ip);
				token = strtok(ip,".");
				token = strtok(NULL,".");
				token2 = strtok(NULL,".");
				token3 = strtok(NULL,".");
				printf("token2: %s\n",token2);
				dadd1 = atoi(token2);
				dadd2 = atoi(token3);
				printf("da1 is: %d\nda2 is: %d\n",da1,da2);
				if(dadd1 == a && dadd2 == b)
				{
					printf("You received data: "); 
					printf("%s\n",trainingMsg4);
				}
				
			break;
			case 5: printf("Received an incoming Frame\n");
			break;
			case 6: printf("Received an idle up Frame\n");
			break;
			case 11: printf("Received a training message Frame\n");
			break;
			default: printf("I don't know what was sent\n");
			break;
		}
		
		memset(messageType,0,sizeof messageType);
		myFrame = NULL;
		memset(message_data,0,sizeof message_data);
		memset(msgType,0,sizeof msgType);
		memset(trainingMsg2,0,sizeof trainingMsg2);
		memset(trainingMsg3,0,sizeof trainingMsg3);
		memset(trainingMsg4,0,sizeof trainingMsg4);
		memset(base,0,sizeof base);

    }
     
    close(sock);
    return 0;
}
int server_connect(int doConnect)
{
    int16_t packet_length;
    char host[30];  // temp space for hostname string

    serverConnected = 0;

    if (doConnect)
    {
        sprintf(host, THINGFABRIC_BROKER_HOSTNAME);
        char *hostname = host;
        hostname_to_ip(hostname , broker_ip);

        if ((broker_ip == NULL) || (broker_ip[0] == 0))
        {
            return 0;
        }

        printf("\n%s resolved to %s\n" , hostname , broker_ip);

        sleep(5);

        // now connect using user/password, publish sensor values on
        // appropriate topic (<domain>/<device type>/<device id>
        char clientIDStr[100];
        sprintf(clientIDStr, "%s/%s", THINGFABRIC_DEVICE_TYPE, THINGFABRIC_DEVICE_ID);
        mqtt_init(&broker, clientIDStr);
        mqtt_init_auth(&broker, THINGFABRIC_USERNAME, THINGFABRIC_PASSWORD);
        init_socket(&broker, broker_ip, THINGFABRIC_BROKER_PORT);

        serverConnected = 1;

        mqtt_connect(&broker);
        // wait for CONNACK
        packet_length = read_packet(1);
        if(packet_length < 0)
        {
            fprintf(stderr, "Error(%d) on read packet!\n", packet_length);
            serverConnected = 0;
        }

        if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_CONNACK)
        {
            fprintf(stderr, "CONNACK expected!\n");
            serverConnected = 0;
        }

        if(packet_buffer[3] != 0x00)
        {
            fprintf(stderr, "CONNACK failed!\n");
            serverConnected = 0;
        }

        if (serverConnected)
        {
            sprintf(pubTopic, "%s/%s/%s", THINGFABRIC_DOMAIN, THINGFABRIC_DEVICE_TYPE, THINGFABRIC_DEVICE_ID);
            printf("%s\n", pubTopic);

            // configure the ping timer
            signal(SIGALRM, alive);
            alarm(keepalive);
        }
        else
        {
            fprintf(stderr, "Error connecting to MQTT server\n");
        }
    }
    else
    {
        printf("Disconnecting from server\n");
        mqtt_disconnect(&broker);
        close_socket(&broker);
        serverConnected = 0;
    }

    return serverConnected;
}
Exemple #17
0
int main(int argc, char **argv) {
	int i;
	if(argc < 3) {
		printf("Usage: ./mine <node url> [<plot dir> <plot dir> ..]\n");
		exit(-1);
	}

#ifdef SOLO
	// Reading passphrase from file
	int pf = open( "passphrases.txt", O_RDONLY );
	if( pf < 0 ) {
		printf("For solo mining: could not find file passphrases.txt\nThis file should contain the passphrase used to create the plotfiles\n");
		exit(-1);
	}
	
	int bytes = read( pf, passphrase, 2000 );

	// Replace spaces with +
	for( i=0; i<bytes; i++ ) {
		if( passphrase[i] == ' ' )
			passphrase[i] = '+';

		// end on newline
		if( passphrase[i] == '\n' || passphrase[i] == '\r')
			passphrase[i] = 0;
	}

	passphrase[bytes] = 0;
#endif

	// Check if all directories exist:
	struct stat d = {0};

	for(i = 2; i < argc; i++) {
		if ( stat( argv[i], &d) ) {
			printf( "Plot directory %s does not exist\n", argv[i] );
			exit(-1);
		} else {
			if( !(d.st_mode & S_IFDIR) ) {
				printf( "%s is not a directory\n", argv[i] );
				exit(-1);
			}
		}
	}
	
	char *hostname = argv[1];

	// Contains http://? strip it.
	if(strncmp(hostname, "http://", 7) == 0)
		hostname += 7;

	// Contains Port? Extract and strip.
	char *p = strstr(hostname, ":");
	if(p != NULL) {
		p[0] = 0;
		p++;
		nodeport = atoi(p);
	}

	printf("Using %s port %i\n", hostname, nodeport);

	hostname_to_ip(hostname, nodeip);

	memset(oldSignature, 0, 33);

	pthread_t worker[argc];
	time(&starttime);

	// Get startpoint:
	update();	

	// Main loop
	for(;;) {
		// Get scoop:
		char scoopgen[40];
		memmove(scoopgen, signature, 32);

		char *mov = (char*)&height;

		scoopgen[32] = mov[7]; scoopgen[33] = mov[6]; scoopgen[34] = mov[5]; scoopgen[35] = mov[4]; scoopgen[36] = mov[3]; scoopgen[37] = mov[2]; scoopgen[38] = mov[1]; scoopgen[39] = mov[0];

		shabal_context x;
		shabal_init(&x, 256);
		shabal(&x, scoopgen, 40);
		char xcache[32];
		shabal_close(&x, 0, 0, xcache);
		
		scoop = (((unsigned char)xcache[31]) + 256 * (unsigned char)xcache[30]) % HASH_CAP;

		// New block: reset stats
		best = bestn = deadline = bytesRead = 0;

#ifdef SHARE_POOL
		sharefill = 0;
#endif

		for(i = 2; i < argc; i++) {
			if(pthread_create(&worker[i], NULL, work_i, argv[i])) {
				printf("\nError creating thread. Out of memory? Try lower stagger size\n");
				exit(-1);
			}
		}

#ifdef SHARE_POOL
	// Collect threads back in for dev's pool:
                for(i = 2; i < argc; i++)
                       pthread_join(worker[i], NULL);

		if(sharefill > 0) {
			char *f1 = (char*) malloc(SHARECACHE * 100);
			char *f2 = (char*) malloc(SHARECACHE * 100);

			int used = 0;
			for(i = 0; i<sharefill; i++)
				used += sprintf(&f1[used], "%llu:%llu\n", sharekey[i], sharenonce[i]);

			
			int ilen = 1, red = used;
			while(red > 10) {
				ilen++;
				red /= 10;
			}

			int db = sprintf(f2, "POST /pool/submitWork HTTP/1.0\r\nHost: %s:%i\r\nContent-Type: text/plain;charset=UTF-8\r\nContent-Length: %i\r\n\r\n{\"%s\", %u}", nodeip, nodeport, used + 6 + ilen , f1, used);

			printf("\nServer response: %s\n", contactWallet(f2, db));
			
			free(f1);
			free(f2);
		}
#endif

		memmove(oldSignature, signature, 32);
	
		// Wait until block changes:
		do {
			update();
			
			time_t ttime;
			time(&ttime);
#ifdef SHARE_POOL
			printf("\r%llu MB read/%llu GB total/%i shares@target %llu                 ", (bytesRead / ( 1024 * 1024 )), (bytesRead / (256 * 1024)), sharefill, targetdeadline);
#else
			if(deadline == 0)	
				printf("\r%llu MB read/%llu GB total/no low enough deadline yet", (bytesRead / ( 1024 * 1024 )), (bytesRead / (256 * 1024)));
			else 
				printf("\r%llu MB read/%llu GB total/deadline %llus (%llis left)", (bytesRead / ( 1024 * 1024 )), (bytesRead / (256 * 1024)), deadline, (long long)deadline + (unsigned int)starttime - (unsigned int)ttime);
#endif

			fflush(stdout);

			struct timespec wait;
			// Query faster when solo mining
#ifdef SOLO
			wait.tv_sec = 1;
#else 
			wait.tv_sec = 5;
#endif
			wait.tv_nsec = 0;
			nanosleep(&wait, NULL);
		} while(memcmp(signature, oldSignature, 32) == 0);	// Wait until signature changed

		printf("\nNew block %llu, basetarget %llu \n", height, baseTarget);
		fflush(stdout);

		// Remember starttime
		time(&starttime);

#ifndef SHARE_POOL
		// Tell all threads to stop:
		stopThreads = 1;
		for(i = 2; i < argc; i++)
		       pthread_join(worker[i], NULL);

		stopThreads = 0;
#endif
	}
}
char *hostname_to_private_ip4(char *hostname)
{
   return  hostname_to_ip(hostname);
}
Exemple #19
0
int main (int argc, char **argv)
{
  // establish necessary variables here
  int sockfd, n;		// socket and received buffer length

  if (argc != 4)
    {
      printf ("Incorrect Arguments!\n");
      printf ("usage: client <host> <port> <filename>\n");
      exit (1);
    }

  if ((sockfd = socket (AF_INET, SOCK_STREAM, 0)) == -1)
    {
      printf ("Error creating socket\n");
      exit (1);
    }

  // to convert host name (returns original IP or hostname converted to IP)
  char *host = hostname_to_ip (argv[1]);

  // set up all the network stuff
  struct sockaddr_in servaddr, cliaddr;
  bzero (&servaddr, sizeof (servaddr));
  servaddr.sin_family = AF_INET;
  servaddr.sin_addr.s_addr = inet_addr (host);
  servaddr.sin_port = htons (atoi (argv[2]));

  if (connect (sockfd, (struct sockaddr *) &servaddr, sizeof (servaddr)) ==
      -1)
    {
      printf ("Error creating a connection with the server\n");
      exit (1);
    }

  /* send the message to the server */
  short int length = htons (strlen (argv[3]));
  n = write (sockfd, &length, sizeof (length));
  n = write (sockfd, argv[3], strlen (argv[3]));

  int file_size;
  n = read (sockfd, &file_size, sizeof (file_size));
  if (n < 0)
    error ("ERROR reading from socket");
  file_size = ntohl (file_size);
  //printf("Response read from the server: %d\n", file_size);

  if (file_size == 0)
    {
      printf ("File does not exist on the server\n");
      exit (1);
    }

  unsigned char server_hash[16];
  n = read (sockfd, &server_hash, sizeof (server_hash));
  if (n < 0)
    error ("ERROR reading from socket");

  int i;
	/*
  printf ("Server Hash: ");
  for (i = 0; i < mhash_get_block_size (MHASH_MD5); i++)
    {
      printf ("%.2x", server_hash[i]);
    }
  printf ("\n");
	 */

  FILE *file;
  file = fopen (argv[3], "w+");
  if (file == NULL)
    {
      printf ("Could not open file\n");
      exit (1);
    }

  char output[BUF_LEN];
  bzero (output, BUF_LEN);
  int downloaded = 0;
  int buffer_size;
  struct timeval start;
  struct timeval finish;
  gettimeofday(&start,NULL);
  while (downloaded < file_size)
    {
	  if ((file_size-downloaded)>=BUF_LEN)
	  {
		  buffer_size=BUF_LEN;
	  }else{
		  buffer_size=(file_size-downloaded);
	  }
      n = read (sockfd, output, buffer_size);
      fwrite (output, sizeof (char), buffer_size, file);
      bzero (output, buffer_size);
      downloaded += buffer_size;
    }
  gettimeofday(&finish,NULL);
	long microsecs_elapsed = ((finish.tv_sec - start.tv_sec)*1000000L
						  +finish.tv_usec) - start.tv_usec;
	float time_elapsed = (float)microsecs_elapsed/1000000;

  rewind (file);

	MHASH td;
	unsigned char buffer;
	unsigned char client_hash[16];
	
	td = mhash_init (MHASH_MD5);
	
	while (fread (&buffer, 1, 1, file) == 1)
    {
		mhash (td, &buffer, 1);
    }
	mhash_deinit (td, client_hash);

	/*
  printf ("Client Hash: ");
  for (i = 0; i < mhash_get_block_size (MHASH_MD5); i++)
    {
      printf ("%.2x", client_hash[i]);
    }
  printf ("\n");
	 */
	 
  fclose (file);

  if (compare_hash (server_hash, client_hash) == 0)
    {
      printf ("File transfer was unsuccessful\n");
      remove (argv[3]);
      exit (1);
    }
	
  printf("%d bytes transferred in %.6f seconds: %.6f MB/sec\n",file_size,time_elapsed,
		 (float)(file_size/1048576)/time_elapsed);
	printf("File MD5sum: ");
	for (i = 0; i < mhash_get_block_size (MHASH_MD5); i++)
    {
		printf ("%.2x", client_hash[i]);
    }
	printf ("\n");

  close (sockfd);
  return 0;
}
Exemple #20
0
//method that talks with the browser
void *client_handler(void *sock_desc) {
	int msg_size;
	char buf[BUF_SIZE], request[BUF_SIZE];
	int sock = *(int*)sock_desc;
	
	while ((msg_size = recv(sock, buf, BUF_SIZE, 0)) > 0) {
        buf[msg_size] = 0;
		
		//figure out what we want to get
		char tokenize[msg_size+1];
		strcpy(tokenize, buf);
		
		char * token = strtok(tokenize, " ");
		token = strtok(NULL, " ");
		//complete address
		char * pch = token + 1;
		char address[200];
		if(pch)
		{
			strcpy(address, pch);
		}
		
		//document path
		char * pch2 = strchr(pch, '/');
		char document[200];
		if(pch2)
		{
			strcpy(document, pch2);
		}
		else
		{
			strcpy(document, "/");
		}
		
		//host or "domain"
		char host[200], ip[100];
		int diff;
		if(pch && pch2)
		{
			diff = pch2 - pch;
		}
		else
		{
			diff = strlen(address);
		}
			
		strncpy(host, address, diff);
		
		//check if site is blocked
		FILE * blacklist;
		char blBuffer[100];
		blacklist = fopen("blacklist.txt", "r");
		int blocked = 0;
		while (fgets(blBuffer, 100, blacklist) != NULL )
		{
			if(strncmp(host, blBuffer, diff) == 0)
			{
				blocked = 1;
				break;
			}
		}
		fclose(blacklist);
		
		if(blocked == 1)
		{
			//this is blocked
			//this whole block of code will read "blocked_response.txt" and send the contents to the browser
			FILE * isBlocked;
			isBlocked = fopen("blocked_response.txt", "r");
			char blockedSend[BUF_SIZE];
			char blockedBuffer[10000];
			while(fgets(blockedBuffer, 10000, isBlocked) != NULL)
			{
				strcat(blockedSend, blockedBuffer);
				memset(blockedBuffer,0,strlen(blockedBuffer));
			
			}
			strcat(blockedSend, "\r\n\r\n");
			sendRes(blockedSend, sock);
			memset(blockedSend,0,strlen(blockedSend));
			
			printf("%s", "This is blocked!");
			fflush(stdout);
			fclose(isBlocked);
		}
		else
		{
			//CHECK FOR CACHE FILE
			FILE * fp;
			fp = fopen(host, "r");
			if(!fp)
			{
				//make the file
				fp = fopen(host, "w");
				//build our request
				strncpy(request, "GET ", 4);
				strcat(request, document);
				strcat(request, " HTTP/1.1\r\nHost: ");
				strncat(request, host, diff);
				strcat(request, "\r\nUser-Agent: WebProxy/0.99");
				strcat(request, "\r\n\r\n");
				host[diff] = '\0';
				hostname_to_ip(host, ip);
		
				printf("%s\n", request);
				
				//send our request
				char * returned = web_handler(ip, request);
				//filter for bad words
				FILE * badwords;
				badwords = fopen("badwords.txt", "r");
				char badBuffer[100];
				while(fgets(badBuffer, 100, badwords) != NULL)
				{
					int length = strlen(badBuffer);
					badBuffer[length-1] = '\0';
					returned = str_replace(returned, badBuffer, "***REMOVED***");
				}
				sendRes(returned, sock);
				//print final version to cache file
				fprintf(fp, "%s", returned);
			}
			else
			{
				//read the file
				char toSend[BUF_SIZE];
				char fileBuffer[10000];
				while(fgets(fileBuffer, 10000, fp) != NULL)
				{
					strcat(toSend, fileBuffer);
					memset(fileBuffer,0,strlen(fileBuffer));
				
				}
				//send cached content to browser
				sendRes(toSend, sock);
				memset(toSend,0,strlen(toSend));
			}
		
			fclose(fp);
		}
		
		memset(buf,0,strlen(buf));
		//memset(address,0,strlen(address));
		memset(document,0,strlen(document));
		memset(ip,0,strlen(ip));
    }

    close(sock);
	free(sock_desc);
	threadCount++;
}
Exemple #21
0
int getServerFromDirectory(int *ip, int *port){

		//Initialize variables
		int sock, result;
		struct sockaddr_in server;

		//Create socket
	    sock = socket(AF_INET , SOCK_STREAM , 0);
	    if (sock == -1)
	    {
	        puts("Could not create socket");
			return -1;
	    }
	    puts("Socket created");

		//Connect to Directory Register and get ip and port for service
		char iptemp[100];
		hostname_to_ip(ServerDirectoryIP, iptemp);
	
		server.sin_addr.s_addr = inet_addr(iptemp);
	    server.sin_family = AF_INET;
	    server.sin_port = htons(ServerDirectoryPort);

		//Connect to Directory Service
		puts("Trying to connect to Directory Service");
		int connected = -1;
		while(connected == -1){
	    	connected = connect(sock , (struct sockaddr *)&server , sizeof(server));
		}

		//Connected to Directory Service
	    puts("Connected");

		//Let Directory know you are the client
		if(sendInt(sock, 0) < 0){
			puts("Send connector type client failed");
			close(sock);
			return -1;
		}

		// Tell the directory there the reason for connecting
		if(sendInt(sock, 1) < 1){
			puts("Send connector type client failed");
			close(sock);
			return -1;
		}

		//Get Status of Server Found or Not
		if(readInt(sock, &result) < 0){
			puts("Receive Query Result failed");
			close(sock);
			return -1;
		}else{
			if(result == 0){
				puts("Server Not Found");
				close(sock);
				return -1;
			}
		}

		printf("Got Result = %d\n",result);

		//Get IP
		if(recv(sock , ip , sizeof(int)*4,0) < 0){
			puts("Receive IP failed");
			close(sock);
			return -1;
		}

		//Send the ACK
		if(sendAck(sock) < 0){
			puts("Send ACK failed");
			close(sock);
			return -1;
		}

		//Get Port
		if(readInt(sock , port) < 0){
			puts("Receive Port failed");
			close(sock);
			return -1;
		}

		//Successful
		//Close connection to Directory Service
		close(sock);
		return 1;
}
Exemple #22
0
static int add_site(char *addr_string, int type)
{
	int rv;
	struct booth_site *site;
	uLong nid;
	uint32_t mask;
	int i;

	rv = 1;
	if (booth_conf->site_count == MAX_NODES) {
		log_error("too many nodes");
		goto out;
	}
	if (strnlen(addr_string, sizeof(booth_conf->site[0].addr_string))
			>= sizeof(booth_conf->site[0].addr_string)) {
		log_error("site address \"%s\" too long", addr_string);
		goto out;
	}

	site = booth_conf->site + booth_conf->site_count;

	site->family = AF_INET;
	site->type = type;

	strncpy(site->addr_string, addr_string, sizeof(site->addr_string));

	if (!(inet_pton(AF_INET, site->addr_string, &site->sa4.sin_addr) > 0) &&
        !(inet_pton(AF_INET6, site->addr_string, &site->sa6.sin6_addr) > 0)) {

		/* Not a valid address, so let us try to convert it into an IP address */
		hostname_to_ip(site->addr_string);
	}

	site->index = booth_conf->site_count;
	site->bitmask = 1 << booth_conf->site_count;
	/* Catch site overflow */
	assert(site->bitmask);
	booth_conf->all_bits |= site->bitmask;
	if (type == SITE)
		booth_conf->sites_bits |= site->bitmask;

	site->tcp_fd = -1;

	booth_conf->site_count++;

	rv = 0;
	memset(&site->sa6, 0, sizeof(site->sa6));

	nid = crc32(0L, NULL, 0);
	/* Using the ASCII representation in site->addr_string (both sizeof()
	 * and strlen()) gives quite a lot of collisions; a brute-force run
	 * from 0.0.0.0 to 24.0.0.0 gives ~4% collisions, and this tends to
	 * increase even more.
	 * Whether there'll be a collision in real-life, with 3 or 5 nodes, is
	 * another question ... but for now get the ID from the binary
	 * representation - that had *no* collisions up to 32.0.0.0.
	 * Note that POSIX mandates inet_pton to arange the address pointed
	 * to by "dst" in network byte order, assuring little/big-endianess
	 * mutual compatibility. */
	if (inet_pton(AF_INET,
				site->addr_string,
				&site->sa4.sin_addr) > 0) {

		site->family = AF_INET;
		site->sa4.sin_family = site->family;
		site->sa4.sin_port = htons(booth_conf->port);
		site->saddrlen = sizeof(site->sa4);
		site->addrlen = sizeof(site->sa4.sin_addr);
		site->site_id = crc32(nid, (void*)&site->sa4.sin_addr, site->addrlen);

	} else if (inet_pton(AF_INET6,
				site->addr_string,
				&site->sa6.sin6_addr) > 0) {

		site->family = AF_INET6;
		site->sa6.sin6_family = site->family;
		site->sa6.sin6_flowinfo = 0;
		site->sa6.sin6_port = htons(booth_conf->port);
		site->saddrlen = sizeof(site->sa6);
		site->addrlen = sizeof(site->sa6.sin6_addr);
		site->site_id = crc32(nid, (void*)&site->sa6.sin6_addr, site->addrlen);

	} else {
		log_error("Address string \"%s\" is bad", site->addr_string);
		rv = EINVAL;
	}

	/* Make sure we will never collide with NO_ONE,
	 * or be negative (to get "get_local_id() < 0" working). */
	mask = 1 << (sizeof(site->site_id)*8 -1);
	assert(NO_ONE & mask);
	site->site_id &= ~mask;


	/* Test for collisions with other sites */
	for(i=0; i<site->index; i++)
		if (booth_conf->site[i].site_id == site->site_id) {
			log_error("Got a site-ID collision. Please file a bug on https://github.com/ClusterLabs/booth/issues/new, attaching the configuration file.");
			exit(1);
		}

out:
	return rv;
}
Exemple #23
0
//there should be lock handle, such as global_stat_spin, but I just don't want to implement it now.
int update_peer_table(struct peer_profile_t** peer_table, FILE *secrets_file, int max_id)
{
    if(NULL == peer_table || NULL == secrets_file)
    {
        ERROR(0, "update_peer_table: peer_table or secrets_file is NULL");
        return -1;
    }
    
    int i;
    for(i = 0; i < max_id+1; i++)
        if(peer_table[i] != NULL)
            peer_table[i]->discard = true;

    size_t len = 1024;
    char *line = (char *)malloc(len);
    if(line == NULL)
    {
        ERROR(errno, "update_peer_table: malloc failed");
        return -1;
    }
    else
        bzero(line, len);

    while(-1 != getline(&line, &len, secrets_file))  //why line is an array of char*, not a char* ?
    {
        int id = 0;
        char *id_str = NULL;
        char *psk_str = NULL;
        char *ip_name_str = NULL;
        char *ip6_str = NULL;
        char *port_str = NULL;

        if(shrink_line(line) <= 1)
            continue;
        id_str = strtok(line, " ");
        psk_str = strtok(NULL, " ");
        ip_name_str = strtok(NULL, " ");
        ip6_str = strtok(NULL, " ");
        port_str = strtok(NULL, " ");

        if(NULL == id_str)
            continue;
        if(NULL == psk_str)
        {
            WARNING("PSK of ID %s not found, ignore this peer!", id_str);
            continue;
        }
        id = inet_ptons(id_str);
        if(0 == id || id > max_id)
        {
            WARNING("The ID of %s may be wrong, ignore this peer!", id_str);
            continue;
        }
        
        struct peer_profile_t * tmp_peer = add_peer();
        if(tmp_peer == NULL)
        {
            ERROR(errno, "update_peer_table: add_peer failed.");
            return -1;
        }
        if(peer_table[id] != NULL)
            if(copy_peer(tmp_peer, peer_table[id]) < 0)
                ERROR(0, "Copy the ID of %s failed.", id_str);

        tmp_peer->id = id;
        tmp_peer->discard = false;

        if(strlen(psk_str) > 2*AES_TEXT_LEN)
            WARNING("PSK of ID %s is longer than %d, ignore some bytes.", id_str, 2*AES_TEXT_LEN);
        strncpy((char*)tmp_peer->psk, psk_str, 2*AES_TEXT_LEN);

        if(port_str != NULL) //port_str must be parsed before ip, because servaddr.sin_port uses it.
        {
            int port = atoi(port_str);
            if(port < 1)
                WARNING("Invalid PORT of peer: %s, ingore it's port value!", id_str);
            tmp_peer->port = port;
        }

        if(ip_name_str != NULL && strcmp(ip_name_str, "none") != 0)
        {
            char ip_str[IPV4_LEN] = "\0";
            if(hostname_to_ip(ip_name_str, ip_str) < 0)
                WARNING("Invalid host of peer: %s, %s nslookup failed, ingore it's IP/Port value!", id_str, ip_name_str);
            else
            {
                inet_pton(AF_INET, ip_str, &(tmp_peer->peeraddr->sin_addr));
                tmp_peer->peeraddr->sin_family = AF_INET;
                tmp_peer->peeraddr->sin_port = htons(tmp_peer->port);
                tmp_peer->restricted = true;
            }
        }

        if(ip6_str != NULL && strcmp(ip6_str, "none") != 0)
            WARNING("IPv6 not supported now, ignore it!");

        tmp_peer->vip = htonl(id); //0.0.x.x in network byte order, used inside tunnel.
        //tmp_peer->rip = (global_tunif.addr & global_tunif.mask) | htonl(id); //in network byte order.

        if(peer_table[id] != NULL &&
            tmp_peer->peeraddr->sin_addr.s_addr == peer_table[id]->peeraddr->sin_addr.s_addr &&
            tmp_peer->peeraddr->sin_port == peer_table[id]->peeraddr->sin_port &&
            strncmp((char *)(tmp_peer->psk), (char *)(peer_table[id]->psk), 2*AES_TEXT_LEN) == 0)
        {
            //the peer does not change
            peer_table[id]->discard = false;
            delete_peer(tmp_peer);
            tmp_peer = NULL;
            continue;
        }

        if(peer_table[id] != NULL)
        {
            INFO("update the ID of %s.", id_str);
            if(copy_peer(peer_table[id], tmp_peer) < 0)
                ERROR(0, "Update the ID of %s failed", id_str);
            delete_peer(tmp_peer);
            tmp_peer = NULL;
        }
        else
        {
            INFO("Add the ID of %s.", id_str);
            peer_table[id] = tmp_peer;
        }
    }

    free(line);

    for(i = 0; i < max_id+1; i++)
        if(peer_table[i] != NULL)
            if(peer_table[i]->discard)
            {
                WARNING("Delete the ID of %d.%d.", i/256, i%256);
                delete_peer(peer_table[i]);
                peer_table[i] = NULL;
            }

    return 0;
}
Exemple #24
0
int output_stream::add(char* target, map_pidtype &pids)
{
	char *save;
	char *ip = NULL;
	uint16_t port = 0;
	bool b_tcp = false;
	bool b_udp = false;
	bool b_file = false;

	dPrintf("(-->%s)", target);

	size_t len = strlen(target);
	strncpy(name, target, sizeof(name)-1);
	name[len < sizeof(name) ? len : sizeof(name)-1] = '\0';

	if ((0 == strcmp(target, "-")) ||
	    (0 == strcmp(target, "fd://0")) ||
	    (0 == strcmp(target, "fd:/0")))
		return add_stdout(pids);
	else
	if (strstr(target, ":")) {
		ip = strtok_r(target, ":", &save);
		if (strstr(ip, "tcp"))
			b_tcp = true;
		else
		if (strstr(ip, "udp"))
			b_udp = true;
		else
		if (strstr(ip, "file"))
			b_file = true;

		if ((b_tcp) || (b_udp) || (b_file)) {
			ip = strtok_r(NULL, ":", &save);
			if (strstr(ip, "//") == ip)
				ip += 2;
		}
		// else ip = proto;
		if (!b_file)
			port = atoi(strtok_r(NULL, ":", &save));
	} else {
		b_tcp = false;
		ip = target;
		port = 1234;
	}

	if (sock >= 0)
		close(sock);

	if (b_file) {
		dPrintf("opening %s...", ip);
		if ((sock = open(ip, O_CREAT|O_WRONLY|O_TRUNC, S_IRWXU)) < 0) {
			perror("file failed");
			return -1;
		} else {
			ringbuffer.reset();
			stream_method = OUTPUT_STREAM_FILE;
			return set_pids(pids);
		}
	}

	sock = socket(AF_INET, (b_tcp) ? SOCK_STREAM : SOCK_DGRAM, (b_tcp) ? IPPROTO_TCP : IPPROTO_UDP);
	if (sock >= 0) {

		socket_set_nbio(sock);

		char resolved_ip[16] = { 0 };
		if (0 == hostname_to_ip(ip, resolved_ip, sizeof(resolved_ip)))
			ip = &resolved_ip[0];

		if (!priv) priv = new output_stream_priv;
		priv->ip_addr.sin_family = AF_INET;
		priv->ip_addr.sin_port   = htons(port);
#if (!defined(HAVE_INET_PTON) && !defined(HAVE_INET_ATON) && !defined(HAVE_INETPTON))
		if (getnameinfo((struct sockaddr*)&priv->ip_addr, sizeof(struct sockaddr),
			ip, NI_MAXHOST, NULL, NI_MAXSERV, NI_NUMERICHOST) != 0)
#else
#ifndef HAVE_INET_PTON
#define inet_pton(a,b,c) InetPton(a,b,c)
#endif
#ifndef HAVE_INET_ATON
#define inet_aton(a,b) inet_pton(AF_INET,a,b)
#endif

		if (inet_aton(ip, &priv->ip_addr.sin_addr) == 0)
#endif
		{
			perror("ip address translation failed");
			return -1;
		} else
			ringbuffer.reset();

		if (b_tcp) {
			if (((connect(sock, (struct sockaddr *) &priv->ip_addr, sizeof(priv->ip_addr)) < 0) && (errno != EINPROGRESS))
#if defined (_WIN32)
				&& (WSAGetLastError() != WSAEWOULDBLOCK)
#endif
			) {
				perror("failed to connect to server");
				return -1;
			}
			stream_method = OUTPUT_STREAM_TCP;
		} else {
			stream_method = OUTPUT_STREAM_UDP;
		}
	} else {
		perror("socket failed");
		return -1;
	}
	dPrintf("~(-->%s)", target);

	return set_pids(pids);
}
int main(int argc, char **argv){
	
	if(argc != 9){
		printf("Usage ./p4 N b c F B P S T %d\n", argc);
		exit(0);
	}
	
	N = atoi(argv[1]);
	b = atoi(argv[2]);
	c = atoi(argv[3]);
	F = atoi(argv[4]);
	B = atoi(argv[5]);
	P = atoi(argv[6]);
	S = atoi(argv[7]);
	T = atoi(argv[8]);
	
	node_list = (gossip_node*)malloc(sizeof(gossip_node)*N);
	neighbour_list = (gossip_node*)malloc(sizeof(gossip_node)*b);
		
	struct sockaddr_in remaddr;	
	socklen_t addrlen = sizeof(remaddr);		
	int recvlen;		
	unsigned char buf[BUFSIZE];	

	pthread_mutex_init(&mutex, NULL);
	
	/*Creating a socket*/
	if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
		perror("socket failed\n");
		return 0;
	}

	memset((char *)&myaddr, 0, sizeof(myaddr));
	myaddr.sin_family = AF_INET;
	myaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	myaddr.sin_port = htons(0);
	
	/*Binding to a socket*/
	if (bind(fd, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) {
		perror("bind failed");
		return 0;
	}
	
	socklen_t len = sizeof(myaddr);
	if (getsockname(fd, (struct sockaddr *)&myaddr, &len) == -1)
		perror("getsockname");
	
	char hostname[1024];
	char ip[100];
	hostname[1023] = '\0';
	gethostname(hostname, 1023);
	printf("Hostname: %s\n", hostname);
	struct hostent* h;
	h = gethostbyname(hostname);
	hostname_to_ip(h->h_name,ip);
	printf("IP Address: %s\n", ip);
	printf("Port number %d\n", ntohs(myaddr.sin_port));	
	
	
	/*Reading lines in endpoints.txt file */
	FILE *fp1= fopen("endpoints.txt", "ab+");
	int lines = 0;
	char ch;
	while(!feof(fp1)){
		ch = fgetc(fp1);
		if(ch == '\n'){
			lines++;
		}
	}
	
	my_line_number = lines;
	
	/* Creating 2 random buffers based on 2 different seeds [S, S+I] */
	char *rand_buf1 = (char*)calloc(64, sizeof(char));
	char *rand_buf2 = (char*)calloc(64, sizeof(char));
	si_buf = (struct random_data*)calloc(1,sizeof(struct random_data));
	s_buf = (struct random_data*)calloc(1,sizeof(struct random_data));
	initstate_r(S+my_line_number,rand_buf1, 64, si_buf);
	initstate_r(S,rand_buf2, 64, s_buf);
	srandom_r(S+my_line_number, si_buf);
	srandom_r(S, s_buf);
	
	fclose(fp1);
	FILE *fp = fopen("endpoints.txt", "ab+");
	int i;
	size_t buffsize = 150;
	char *line = malloc(sizeof(char)*buffsize);
	
	/*Last node check */
	if(lines == N-1){
		/*Send OK to all the other nodes*/
		fprintf(fp, "%s:%d\n", ip, ntohs(myaddr.sin_port));
		rewind(fp);
		for (i=0; i < N-1; i++) {
			int num = getline(&line, &buffsize, fp);
			printf("Line: %s\n",line);
			char ip[100];
			char port[50];
			int ipdone = 0;
			int j;
			int w;
			for(w=0; w<num; w++){
				if(line[w] != ':' && !ipdone)
					ip[w] = line[w];
				else{
					ipdone = 1;
					ip[w] = '\0';
					j = ++w;
					break;
				}
			}
			int k;
			for(w=0, k=j; k<num; w++, k++){
				port[w] = line[k];
			}
			port[w] = '\0';
			
			memset((char *) &remaddr, 0, sizeof(remaddr));
			remaddr.sin_family = AF_INET;
			remaddr.sin_port = htons(atoi(port));
			remaddr.sin_addr.s_addr = inet_addr(ip);
			sprintf(buf, "OK");
			sendto(fd, buf, strlen(buf), 0, (struct sockaddr *)&remaddr, addrlen);
		}
		fclose(fp);
	} else {
		/*Not the last node - add to endpoints file and wait for OK */
		fprintf(fp, "%s:%d\n", ip, ntohs(myaddr.sin_port));
		fclose(fp);
		recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
		printf("Receiver IP : %s\n", inet_ntoa(remaddr.sin_addr));
		printf("received %d bytes\n", recvlen);
		if (recvlen > 0) {
			buf[recvlen] = 0;
			printf("received message: \"%s\"\n", buf);
		}
	}
	
	/*OK received - creating node_list from endpoints file */
	FILE *fp2 = fopen("endpoints.txt", "ab+");
	for (i=0; i < N; i++) {
		int num = getline(&line, &buffsize, fp);
		char ip[100];
		char port[50];
		int ipdone = 0;
		int j;
		int w;
		for(w=0; w<num; w++){
			if(line[w] != ':' && !ipdone)
				ip[w] = line[w];
			else{
				ipdone = 1;
				ip[w] = '\0';
				j = ++w;
				break;
			}
		}
		int k;
		for(w=0, k=j; k<num; w++, k++){
			port[w] = line[k];
		}
		port[w] = '\0';
		gossip_node new_node;
		new_node.port = atoi(port);
		new_node.status = 1;
		new_node.heartbeat = 0;
		strcpy(new_node.ip, ip);
		node_list[i] = new_node;
	}
	
	for(i=0; i<N; i++){
		printf("Node %d: %s %d %d %d\n",i, node_list[i].ip, node_list[i].port, node_list[i].status, node_list[i].heartbeat);
	}
	printf("\n\n");
	
	pthread_t serverthread;
	
	/* Starting server thread */
	pthread_create(&serverthread,NULL, server_handler, &myaddr);
	i=0;
	int send_msges = 1;
	
	/* Sending messages for c iterations */
	while(1){
		
		if(send_msges){
			pthread_mutex_lock(&mutex);
			int j;
			int neighbour_count = 0;
			/*Randomly find b neighbours to send a message*/
			while(neighbour_count < b){
				int32_t send_index;
				random_r(si_buf, &send_index);
				send_index = send_index%N;
				//printf("Random Index : %d\n", send_index);
				if(!contains_neighbour(send_index, neighbour_list, neighbour_count)){
					gossip_node new_node;
					new_node.port = node_list[send_index].port;
					new_node.status = node_list[send_index].status;
					new_node.heartbeat = node_list[send_index].heartbeat;
					strcpy(new_node.ip, node_list[send_index].ip);
					neighbour_list[neighbour_count] = new_node;
					neighbour_count++;
				}
			}
			for(j=0; j<b; j++){
				memset((char *) &remaddr, 0, sizeof(remaddr));
				remaddr.sin_family = AF_INET;
				remaddr.sin_port = htons(neighbour_list[j].port);
				remaddr.sin_addr.s_addr = inet_addr(neighbour_list[j].ip);
				//printf("Sending packet %d to %s port %d\n", j, neighbour_list[j].ip, neighbour_list[j].port );
				//sprintf(buf, "Sending list");
				char buffer[50*N];
				node_list_to_char_arr(node_list, buffer, N);
				sendto(fd, buffer, strlen(buffer), 0, (struct sockaddr *)&remaddr, addrlen);
			}
			pthread_mutex_unlock(&mutex);	
		}
		/*Check localClock for failing myself */
		if(send_msges &&  localClock !=0 && localClock%P == 0){
			if(get_fail_count() < B && fail_myself()){
				printf("FAILING MYSELF %d\n",localClock);
				send_msges = 0;
				node_list[my_line_number].status = 0;
			}
		}
		i++;
		sleep(1);
		localClock++;
		printf("Localclock : %d\n", localClock);
		node_list[my_line_number].heartbeat = localClock;
		
		/*If c iterations completed or Time T is reached exit the send loop */
		if(i==c || localClock >= T)
			break;
	}
	
	/*If c iterations completed before T, wait till localClock reaches T seconds */
	while(localClock < T){
		sleep(1);
		localClock++;
	}
	
	/*Write the final output to listX file */
	char fileName[10];
	sprintf(fileName, "list%d.txt", my_line_number);
	FILE *fp_new = fopen(fileName, "ab+");
	fprintf(fp_new, "%s\n", node_list[my_line_number].status == 0 ? "FAIL" : "OK");
	int index;
	for(i=0; i<N; i++){
		fprintf(fp_new, "%d %d\n", i, node_list[i].heartbeat);
	}
	fclose(fp_new);
	
	for(i=0; i<N; i++){
		printf("FINAL NODE LIST\n");
		printf("Node %d: IP-%s Port-%d Status-%d Heartbeat-%d\n",i, node_list[i].ip, node_list[i].port, node_list[i].status, node_list[i].heartbeat);
	}
}