void *bcast(void *arg){

struct cShared *sh = (struct cShared *)arg;
//char *msg= (char *)msg1;
mySendingPort *my_send_port1 = sh-> my_send_port;

while(1){
  Packet *my_packet = new Packet();
  PacketHdr *hdr = my_packet->accessHeader();
  hdr->setOctet(ANNOUNCEMENT,0);

  cout<<"into thread"<<endl;
  list<int>::iterator p1 = list1.begin();
  while(p1 != list1.end()){
      
      hdr->setOctet((unsigned char)(*p1),1);
      cout<<"sending pkt "<<*p1<<endl;
      //my_send_port1->setACKflag(true);
      my_send_port1->sendPacket(my_packet);
      
      p1++;
      
  }

//  sem_wait(&mutex);
  pthread_mutex_lock(&lock);
 // cout<<msg<<endl;
  pthread_mutex_unlock(&lock);
//  sem_post(&mutex);
  sleep(10);
  }
return 0;

}
void *MakeAnnouncementPacket(void *arg){
    cout << "Start: Make announcement function." <<endl;
    
    struct SPShared *sp = (struct SPShared *)arg;
    while(1){
        
        int i;
        Packet *packet = new Packet();
        PacketHdr *hdr;
        
        for(i = 0; i< ListOfContents.size(); i++){
            packet = new Packet();
            hdr = packet->accessHeader();
            hdr->setOctet('2',0);
            hdr->setOctet(ListOfContents.at(i),1);
            hdr->setOctet(0,2);
           
            sp->send_port->sendPacket(packet);
            //sp->send_port->setACKflag(true);
            //sp->send_port->timer_.startTimer(0);
        }

        usleep(10000000);
    }
}
Exemplo n.º 3
0
Packet *Message::make_response_packet(int CID, int HID, const char *filename){
	Packet * response_packet;
	response_packet = new Packet();

	//get some info of the file
	//read file
	ifstream f1(filename);
	f1.seekg(0, ios::end);
	int len = (int)f1.tellg();
	f1.seekg(0, f1.beg);
	char *datachunk = new char[len];
	f1.read(datachunk, len);
	f1.close();

	//Header
	PacketHdr *hdr = response_packet->accessHeader();
	hdr->setOctet(TYPE_RESPONSE, POS_TYPE );
	hdr->setOctet(CID, POS_CID );
	hdr->setOctet(HID, POS_HID );
	hdr->setShortIntegerInfo(len, POS_SIZE);

	// fill payload by content...
	response_packet->fillPayload(len, datachunk);

	return response_packet;
}
Exemplo n.º 4
0
int* Router::forward_rxed_data_packet_to_port(Packet* p){
	PacketHdr *hdr = p->accessHeader();
	char p_type = hdr->getOctet(PACKET_TYPE_INDEX);
	if(p_type != 'm'){ //check for packet type
		std::cout << "This function is supposed to be given DATA packet. This has another type !\n";
		exit(1);
	}
	//Extract necessary info for giving the forwarding decision
	char num_addr = hdr->getOctet(NUM_ADDR_INDEX);
	int int_num_addr = (int)(num_addr-'0');
	int* d_p = new int[int_num_addr];
	char dest_addrs_buffer[int_num_addr+1];
	for(int i=0; i < num_addr; i++){
		dest_addrs_buffer[i]=hdr->getOctet(NUM_ADDR_INDEX+i+1);
	}
	dest_addrs_buffer[num_addr] = (char)'/0';
	/*
	std::cout << "=============================================\n";
	std::cout << "int_num_addr: " << int_num_addr << " dest_addrs_buffer: " 
					  << dest_addrs_buffer << std::endl;
	std::cout << "=============================================\n";
	*/
	if(int_num_addr == 1){//unicast packet
		*d_p = ftf_p->forward_to_port(int_num_addr, (char*)dest_addrs_buffer, &d_p);
	}
	else{ //MC packet
		ftf_p->forward_to_port(int_num_addr, (char*)dest_addrs_buffer, &d_p);
	}	
	return d_p;
}
Exemplo n.º 5
0
Packet* Router::create_control_packet(char p_type){
	Packet * my_packet = new Packet();
	PacketHdr *hdr = my_packet->accessHeader();
	
	if(p_type == 'd'){ //Packet is discovery type
		//Setting the specific header fields
		hdr->setOctet('d',0);
		hdr->setOctet(id,1);

		return my_packet;
	}
	else if(p_type == '1'){
		//Disc Ack packet type is '1'
		hdr->setOctet('1',0);
		hdr->setOctet(id,1);
		
		return my_packet;
	}
	else if(p_type == 'l'){ //Packet is LSP type
		hdr->setOctet('l',0);
		hdr->setOctet('8',1);//TTL
		hdr->setOctet(id,2); //src_addr = id
		hdr->setOctet(num_neighbors,3);
		for(int i=0; i<num_neighbors; i++){
			hdr->setOctet(nbr_tbl.at(i).id[0], 3+i+1);
		}
		++ls_seq_num; //inc for the next ls packet formation
		
		return my_packet;
	}
}
/*!
   \brief Request a certain content by id

   Function to send a packet requesting content and to resend the request if not received on the receiving thread
 */
void GetContent(string contentId, struct res *args)
{
    Packet *req_packet;
    req_packet = new Packet();
    req_packet->setPayloadSize(0); //No Payload

    PacketHdr *rqhdr = req_packet->accessHeader();

    rqhdr->setHeaderSize(3); //Need 3 bytes for the header
    rqhdr->setOctet('0',0); //Request packet = type 0
    rqhdr->setOctet((char)host_id,2); //Setting host id

    int contentId_int = atoi(contentId.c_str());

    rqhdr->setOctet((char)contentId_int,1); //Setting content request message

    args->my_req_port->sendPacket(req_packet);
    args->my_req_port->lastPkt_ = req_packet;
    //cout<<"First octet "<<rqhdr->getOctet(0)<<"Second Octet "<<rqhdr->getOctet(1)<<"Third Octet "<<rqhdr->getOctet(2)<<endl;

    gettimeofday(&rtt, NULL);
    cout<<"Sent Request"<<endl;
    args->my_req_port->setACKflag(false);
    args->my_req_port->timer_.startTimer(5);

    while(!args->my_req_port->isACKed())
    {
        sleep(1);
        if(!args->my_req_port->isACKed())
        {
            sleep(3);
            if(!args->my_req_port->isACKed())
            {
                sleep(5);
                if(!args->my_req_port->isACKed())
                {
                    sleep(7);
                    if(!args->my_req_port->isACKed())
                    {
                        sleep(9);
                        if(!args->my_req_port->isACKed())
                        {
                            cout<<"Giving up.."<<endl;							
                            args->my_req_port->setACKflag(true);
                        }	
                    }
                }
            }
        } 
        else{return;}
    }
    return;
}
Exemplo n.º 7
0
/**
 * Create an ACK message
 */
Packet *Message::make_ack_packet(int seqNum){
	Packet *ack_packet;
	ack_packet = new Packet();
	ack_packet->setPayloadSize(0);

	//Header
	PacketHdr *hdr = ack_packet->accessHeader();
	hdr->setIntegerInfo(RECEIVER_ID, ID_POS);
	hdr->setShortIntegerInfo(ACK_MESSAGE_TYPE, TYPE_POS);
	hdr->setIntegerInfo(seqNum, SEQNUM_POS); // sequence number being ACKED

	return ack_packet;
}
Exemplo n.º 8
0
Packet *Message::make_update_packet(int CID, int nhops){
	Packet * update_packet;
	update_packet = new Packet();
	update_packet->setPayloadSize(0);

	//Header
	PacketHdr *hdr = update_packet->accessHeader();
	hdr->setOctet(TYPE_UPDATE, POS_TYPE );
	hdr->setOctet(CID, POS_CID );
	hdr->setOctet(nhops, POS_HOPS );

	// no payload
	return update_packet;
}
Exemplo n.º 9
0
Packet *Message::make_request_packet(int CID, int HID){
	Packet * request_packet;
	request_packet = new Packet();
	request_packet->setPayloadSize(0);

	//Header
	PacketHdr *hdr = request_packet->accessHeader();
	hdr->setOctet(TYPE_REQUEST, POS_TYPE );
	hdr->setOctet(CID, POS_CID );
	hdr->setOctet(HID, POS_HID );

	// no payload
	return request_packet;
}
void MakeRequest(mySendingPort *my_port, unsigned char content_id){
    
    Packet *new_request_packet = new Packet();
    PacketHdr *hdr = new_request_packet->accessHeader();
    hdr->setOctet('0',0);
    hdr->setOctet(content_id,1);
    hdr->setOctet(HOST_ID,2);
    my_port->sendPacket(new_request_packet);
    cout<<"Packet Sent"<<endl;
    my_port->setACKflag(false);
    my_port->lastPkt_= new_request_packet;
    my_port->timer_.startTimer(10);
    ind->receive_ind = '0';
    ind->content_requested_id = content_id;
    
}
Exemplo n.º 11
0
/**
 * Create a new init message, with the name of the file being transfered
 */
Packet *Message::make_init_packet(char* filename){
	  Packet * init_packet;
	  init_packet = new Packet();
	  init_packet->setPayloadSize(INIT_SIZE);

	  //Header
	  PacketHdr *hdr = init_packet->accessHeader();
	  hdr->setIntegerInfo(SENDER_ID, ID_POS);
	  hdr->setShortIntegerInfo(INIT_MESSAGE_TYPE, TYPE_POS);
	  hdr->setIntegerInfo(0,SEQNUM_POS); //sequence number

	  //Payload
	  int len = strlen(filename);
	  init_packet->fillPayload(len, filename);
	  return init_packet;
}
Exemplo n.º 12
0
void Router::send_ls_to_outgoing_ports(char* incoming_TxP, Packet* p){
	PacketHdr *hdr = p->accessHeader();
	std::cout << "LS packed rxed from node_id" << hdr->getOctet(2) << " is sent to outgoing ports" 
						<< " with TTL:" << hdr->getOctet(1) << std::endl;
	int counter = 0;
	for(int i=0; i<num_neighbors; i++){
		if(strcmp(nbr_tbl.at(i).TxP, incoming_TxP) != 0){ //Do not send it to incoming port
			try{
				++counter;
				txing_ports[i]->sendPacket(p);
			}catch(const char *reason){
				cerr << "Exception:" << reason << endl;
			}
		}
		std::cout << "Incoming LS packet is forwarded to " << counter
							<< " outgoin ports\n";
	}
}
Exemplo n.º 13
0
/**
 * Create a DATA message. seqNum = sequence number of the packet
 */
Packet *Message::make_data_packet(int seqNum){
	Packet *data_packet;
	data_packet = new Packet();

	//Header
	PacketHdr *hdr = data_packet->accessHeader();
	hdr->setIntegerInfo(SENDER_ID, ID_POS);
	hdr->setShortIntegerInfo(DATA_MESSAGE_TYPE, TYPE_POS);
	hdr->setIntegerInfo(seqNum,SEQNUM_POS); //sequence number
	if(seqNum == number_of_packets_){
		hdr->setShortIntegerInfo(1,EOF_POS);
	}else{
		hdr->setShortIntegerInfo(0,EOF_POS);
	}

	//Payload
	int payload_size;
	if(seqNum == number_of_packets_){
		payload_size = length_ - (number_of_packets_ - 1) * DATA_SIZE;
	}
	else{
		payload_size = DATA_SIZE;
	}
	char *data_chunk = new char[payload_size];
	//read the file
	ifstream f1(filename_);
	f1.seekg(0, ios::end);
	int pos = (seqNum - 1) * DATA_SIZE;
	f1.seekg(pos);
	f1.read(data_chunk, payload_size);
	f1.close();
	data_packet->fillPayload(payload_size, data_chunk);
	return data_packet;
}
Exemplo n.º 14
0
void Router::extract_ls_info(Packet* lsp){
	PacketHdr *hdr = lsp->accessHeader();
	char id = hdr->getOctet(2);
	if(std::find(graph_name.begin(), graph_name.end(), id) != graph_name.end()){
		std::cout << "Connectivity info of node_id: " << id << " is already in graph_name\n";
		std::cout << "here comes the graph_name: ";
		for( std::vector<char>::const_iterator i = graph_name.begin(); i != graph_name.end(); ++i)
  	  std::cout << *i << '-';
		std::cout << std::endl;
		return;
	}
	graph_name.push_back(id);
	
	std::cout << "here comes the graph_name: ";
	for( std::vector<char>::const_iterator i = graph_name.begin(); i != graph_name.end(); ++i)
    std::cout << *i << '-';
	std::cout << std::endl;
	
	//Extract the connectivity info
	/*
	//Check the seq_num
	hdr->getOctet(1);
	*/
	int num_nhops = hdr->getOctet(3);
	char* nhops = new char[num_nhops+1];
	for(int i=0; i<num_nhops; i++){
		nhops[i] = hdr->getOctet(3+i+1);
	}
	nhops[num_nhops] = (char)'\0';
	netnode_nhops.insert (std::pair<char,char*>(id, nhops));
	
	
	if(graph_name.size() == num_of_total_nodes){
		std::cout << "CONNECTIVITY INFO FROM EACH NODE IS EXTRACTED YAY !\n";
		build_map();
	}
}	
Exemplo n.º 15
0
void Router::send_data_packet(Packet* p){
	//std::cout << "The following packet ll be sent:" << std::endl;
	//print_data_packet(p);
			
	PacketHdr *hdr = p->accessHeader();
	char num_addr = hdr->getOctet(NUM_ADDR_INDEX);
	int int_num_addr = (int)(num_addr-'0');
	
	
	if(int_num_addr == 1 && hdr->getOctet(NUM_ADDR_INDEX+1) == id){ //if the packet is uni and targeted to me
		std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
		std::cout << "DATA PACKET TARGETED TO ME IS RXED: \n";
		print_data_packet(p);
		std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n";
		return;
	}
	int* f_ports = forward_rxed_data_packet_to_port(p);
	//Use the "goodness" of at most 3 MC receivers
	std::vector <int> ports_done;
	std::vector <char> temp_dests;
	
	for(int i=0; i<int_num_addr; i++){
		int curr_port = f_ports[i];
		temp_dests.clear();
		if(std::find(ports_done.begin(), ports_done.end(), curr_port) == ports_done.end()){ //not contained
			temp_dests.push_back(hdr->getOctet(NUM_ADDR_INDEX+i+1));
			for(int j=i+1; j<int_num_addr; j++){
				if(curr_port == f_ports[j])
					temp_dests.push_back(hdr->getOctet(NUM_ADDR_INDEX+j+1));
			}
			char* dest_addrs = new char[temp_dests.size()+1];
			for(int k=0; k<temp_dests.size(); k++){
				dest_addrs[k] = temp_dests.at(k);
			}
			dest_addrs[temp_dests.size()] = (char)'\0';
			//hdr->getOctet(PAYLOAD_SIZE_INDEX(temp_dests.size()))
			int payload_size = strlen(p->getPayload());
			char* payload = new char[payload_size];
			strcpy(payload, p->getPayload());
			Packet* new_p = create_data_packet('m', (char)((int)(hdr->getOctet(TTL_INDEX)-'0')-1), 
																			hdr->getOctet(SRC_ADDR_INDEX),
																			'0'+temp_dests.size(), dest_addrs,
																			payload_size,	payload);
			send_packet_over_port(new_p, curr_port);
			//std::cout << "The following packet ll be sent over port:" << curr_port << std::endl;
			//print_data_packet(p);
			//
			ports_done.push_back(curr_port);
		}
	}
	
}
Exemplo n.º 16
0
void Router::print_data_packet(Packet* p){
	//First print the header
	PacketHdr *hdr = p->accessHeader();
	
	std::cout << "PRINT PACKET with Header size: " <<hdr->getSize() << "\n";
	std::cout << "packet_type: " <<hdr->getOctet(PACKET_TYPE_INDEX) << "\n";
	std::cout << "ttl: " << hdr->getOctet(TTL_INDEX) << "\n";
	std::cout << "src_addr: " << hdr->getOctet(SRC_ADDR_INDEX) << "\n";
	char num_addr = hdr->getOctet(NUM_ADDR_INDEX);
	std::cout << "num_addr: " << num_addr << "\n";
	
	int int_num_addr = (int)(num_addr-'0');
	char dest_addrs_buffer[int_num_addr+1];
	for(int i=0; i < int_num_addr; i++){
		dest_addrs_buffer[i]=hdr->getOctet(NUM_ADDR_INDEX+i+1);
	}
	dest_addrs_buffer[int_num_addr]='\0';
	std::cout << "dst_addrs: " << dest_addrs_buffer << "\n";
	//Second print the payload
	//std::cout << "payload_size: " << hdr->getOctet(PAYLOAD_SIZE_INDEX(int_num_addr)) << "\n";
	std::cout << "packet_payload: " << p->getPayload() << "\n\n";
}
Exemplo n.º 17
0
Packet* Router::create_data_packet(char p_type, char ttl, char src_addr, char num_addr, 
														 			 char* dest_addrs, int payload_size, char* payload){
	Packet * my_dpacket;
	my_dpacket = new Packet();//create the data packet object
	
	//Settint the specific header fields
	PacketHdr *hdr = my_dpacket->accessHeader();
	hdr->setOctet(p_type,PACKET_TYPE_INDEX);
	hdr->setOctet(ttl,TTL_INDEX);
	hdr->setOctet(src_addr,SRC_ADDR_INDEX);
	hdr->setOctet(num_addr,NUM_ADDR_INDEX);
	int int_num_addr = (int)(num_addr-'0');
	for(int i=0; i<int_num_addr; i++){
		hdr->setOctet(*(dest_addrs+i), NUM_ADDR_INDEX+i+1);
	}
	hdr->setOctet(payload_size,PAYLOAD_SIZE_INDEX(int_num_addr));
	//Fill the packet with the data payload
	my_dpacket->fillPayload(payload_size, payload);
	
	return my_dpacket;
}
Exemplo n.º 18
0
int Message::get_packet_type(Packet *p){
	PacketHdr *hdr = p->accessHeader();
	return (int) hdr->getOctet(POS_TYPE);
}
Exemplo n.º 19
0
void* Router::listen_on_port(void* thread_id){
	int* tid = (int *)(thread_id);
	pthread_mutex_lock( &mutex_lop );
	int tlocal_tid = *tid;
	pthread_mutex_unlock( &mutex_lop );
  cout<<endl<<"Starting to listen on port " << nbr_tbl.at(tlocal_tid).RxP<<"......\n";
  PacketHdr *hdr;

  while(1){
  	Packet* rxed_p = rxing_ports[tlocal_tid]->receivePacket();
  	hdr = rxed_p->accessHeader();
  	if(hdr->getOctet(0) == 'd'){ //Hello packet is rxed
  		cout << "Disc packet is rxed from node_id: " << hdr->getOctet(1)
  				 << " over rx_port:" << nbr_tbl.at(tlocal_tid).RxP << endl;
  		//Send Hello Ack
    	try{
	  		txing_ports[tlocal_tid]->sendPacket(create_control_packet('1'));
		  }catch(const char *reason){
  			cerr << "Exception:" << reason << endl;
  		}
  	}
  	else if(hdr->getOctet(0) == '1'){ //Hello Ack is rxed
  		cout << "Hello Ack is rxed from node_id: " << hdr->getOctet(1)
  				 << " over rx_port:" << nbr_tbl.at(tlocal_tid).RxP << endl;
  		//Set the nhop_hello_ack_rxed map correctly to indicate the ACK is rxed from the nhop
  		nhop_hello_ack_rxed.find(hdr->getOctet(1))->second = 1;
  		/*
  		//print nhop_hello_ack_rxed
  		std::map<char,int>::iterator it;
  		std::cout << "nhop_hello_ack_rxed:\n";
  		for (it=nhop_hello_ack_rxed.begin(); it!=nhop_hello_ack_rxed.end(); ++it){
			if(it->second == 0){
					std::cout << it->first << " -> " << it->second << std::endl;
				}
			}
			*/
  	}
  	else if(hdr->getOctet(0) == 'l'){ //LSP packet is rxed
  		cout << "LSP packet is rxed from node_id: " << hdr->getOctet(2)
  				 << " over rx_port:" << nbr_tbl.at(tlocal_tid).RxP << endl;
  		//Extract the connectivity info
  		extract_ls_info(rxed_p);
  		//Send it to outgoing ports
  		int ttl = (int)(hdr->getOctet(1)-'0');
  		
  		//std::cout << "----------------------------------------\n";
  		//std::cout << "LS TTL: " << hdr->getOctet(1) << std::endl;
  		if( ttl != 0){ //check ttl if it is 0 then discard:dont forward further
  			--ttl;
  			hdr->setOctet( (char)('0'+ttl),1);
  			//std::cout << "UPDATED LS TTL: " << hdr->getOctet(1) << std::endl;	
	  		send_ls_to_outgoing_ports(nbr_tbl.at(tlocal_tid).TxP, rxed_p);
	  	}
	  	//std::cout << "----------------------------------------\n";
	  	
		}
		else if(hdr->getOctet(0) == 'm'){ //Data packet is rxed
			cout << "\nDATA packet is rxed from node_id: " << hdr->getOctet(2)
  				 << " over rx_port:" << nbr_tbl.at(tlocal_tid).RxP << endl;
			forward_incoming_data_packet(rxed_p);
		}
  	else{
  		cout << "Some packet with unrecognized type is rxed\n";
  	}
  }
}
Exemplo n.º 20
0
int Message::get_packet_size(Packet *p){
	PacketHdr *hdr = p->accessHeader();
	return (int) hdr->getShortIntegerInfo(POS_SIZE);

}
Exemplo n.º 21
0
int Message::get_packet_HOPS(Packet *p){
	PacketHdr *hdr = p->accessHeader();
	return (int) hdr->getOctet(POS_HOPS);
}
Exemplo n.º 22
0
void *interface4(void *arg){
	printf("Starting interface4 thread\n");
	struct cShared *sh = (struct cShared *)arg;
	cout<<"This is interface4!"<<endl;

	Packet *recvPacket;
	PacketHdr *hdr;

	char type;
	int cid;
	int hid;
	int hopnum;
	int interface;

	while(1){
		// sleep(0.4);
		recvPacket = sh->recv_port4->receivePacket();
		if(recvPacket!=NULL){
            
		hdr = recvPacket->accessHeader();
		type = hdr->getOctet(0);


		//receive update packet: [type+cid+#hops]
		if(type==(char)0X02){
			int k=0;

			struct routing_Table *temp=new routing_Table;
			struct routing_Table *ptr=NULL;
			cid=hdr->getIntegerInfo(1);
			hopnum=hdr->getIntegerInfo(5);
			temp->CID=cid;
			temp->interf=4;
			temp->hopNum=hopnum;
			temp->nextrow=NULL;
			temp->previous=NULL;
			// updated in 0903 start
			// time_t t=time(0);
			int t=0;
			// updated in 0903 end
			temp->TtoE=t+TTL;

			ptr=sh->rtable;

			//update the routing table
				while(ptr!=NULL){
					if(ptr->CID==temp->CID){
						k=1;
						if(ptr->hopNum >= temp->hopNum){

							ptr->interf=4;
							ptr->hopNum=temp->hopNum;
							ptr->TtoE=temp->TtoE;

							//broadcast updated packet
							hdr->setIntegerInfo(hopnum+1,5);
							sh->send_port2->sendPacket(recvPacket);
							sh->send_port3->sendPacket(recvPacket);
							sh->send_port1->sendPacket(recvPacket);
						}
						else if(ptr->hopNum==temp->hopNum&&ptr->interf==temp->interf){
							ptr->TtoE=temp->TtoE;
						}

					}
						ptr=ptr->nextrow;
				}
				if(k==0){
					temp->nextrow=sh->rtable;
					sh->rtable->previous=temp;
					sh->rtable=temp;

					//broadcast updated packet
					hdr->setIntegerInfo(hopnum+1,5);
					sh->send_port2->sendPacket(recvPacket);
					sh->send_port3->sendPacket(recvPacket);
					sh->send_port1->sendPacket(recvPacket);
				}
			//}
			//delete ptr;

		}
		//receive response packet: [type+cid+hid+payload]
		else if(type==(char)0x01){
			int k=0;
			struct pending_Table *ptr=NULL;
			ptr=sh->ptable;
			cid=hdr->getIntegerInfo(1);
			hid=hdr->getIntegerInfo(5);
			//find the path in pending table
			while(ptr!=NULL){
				if(ptr->rCID==cid && ptr->HID==hid){
					interface=ptr->interf;
					k=1;
					//decided which interface should send the packet
					switch(interface){
						case 1:
							sh->send_port1->sendPacket(recvPacket);
							break;
						case 2:
							sh->send_port2->sendPacket(recvPacket);
							break;
						case 3:
							sh->send_port3->sendPacket(recvPacket);
							break;
						case 4:
							sh->send_port4->sendPacket(recvPacket);
							break;
						default:
							cout<<"Cannot found path!"<<endl;
							break;
					}
				}
				if(k==1)
					break;
			}
			//cout<<"Delivery Error!"<<endl;
			//delete ptr;
		}

		//receive request packet: [type+cid+hid]
		else{
			int k=0;
			int k1=0;

			struct pending_Table *ptemp=new pending_Table;
			struct pending_Table *pptr=NULL;
			struct routing_Table *rptr=NULL;

			cid=hdr->getIntegerInfo(1);
			hid=hdr->getIntegerInfo(5);


			pptr=sh->ptable;
			rptr=sh->rtable;

			ptemp->rCID=cid;
			ptemp->HID=hid;
			ptemp->interf=4;
			// updated in 0903 start
			// time_t t=time(0);
			int t=0;
			// updated in 0903 end
			ptemp->TtoE=t+rTTL;
			ptemp->nextrow=NULL;
			ptemp->previous=NULL;


			//update the pending table
			while(pptr!=NULL){
				if(pptr->rCID==ptemp->rCID && pptr->HID==ptemp->HID){
					k=1;
					//reset TtoE
					break;
				}
				pptr=pptr->nextrow;
			}
			if(k==0){
				ptemp->nextrow=sh->ptable;
				sh->ptable->previous=ptemp;
				sh->ptable=ptemp;
			}
			//figure the path out with routing table


			while(rptr!=NULL){
				if(rptr->CID==ptemp->rCID){
					k1=1;
					interface=rptr->interf;

					//decided which interface should send the packet
					switch(interface){
						case 1:
							sh->send_port1->sendPacket(recvPacket);
							break;
						case 2:
							sh->send_port2->sendPacket(recvPacket);
							break;
						case 3:
							sh->send_port3->sendPacket(recvPacket);
							break;
						case 4:
							sh->send_port4->sendPacket(recvPacket);
							break;
						default:
							cout<<"Cannot found path!"<<endl;
							break;
					}
				}
				if(k1==1)
					break;
				rptr=rptr->nextrow;
			}
			if(k1==0)
				cout<<"Cannot found such content!"<<endl;
			//delete pptr;
			//delete rptr;
			//delete ptemp;
		}
		//delete recvPacket;

		struct routing_Table *p=NULL;
		p=sh->rtable;
		cout<<"The Routing Table is:"<<endl;
		cout<<"ContentID"<<setw(10)<<"Interface"<<setw(6)<<"#Hops"<<setw(5)<<"TtoE"<<endl;
		while(p->nextrow!=NULL){
			cout<<setw(7)<<p->CID<<setw(10)<<p->interf;
			// cout<<setw(5)<<p->hopNum<<setw(7)<<p->TtoE-time(0)<<endl;
			cout<<setw(5)<<p->hopNum<<setw(7)<<p->TtoE-0<<endl;
			p=p->nextrow;
		}

		struct pending_Table *t=NULL;
		t=sh->ptable;
		cout<<"The Pending Table is:"<<endl;
		cout<<"RequstCID"<<setw(7)<<"HostID"<<setw(10)<<"Interface"<<setw(10)<<"TimeToExp"<<endl;
		while(t->nextrow!=NULL){
			cout<<setw(7)<<t->rCID<<setw(7)<<t->HID;
			// cout<<setw(9)<<t->interf<<setw(10)<<t->TtoE-time(0)<<endl;
			cout<<setw(9)<<t->interf<<setw(10)<<t->TtoE-0<<endl;
			t=t->nextrow;
		}
		}
	}
	return NULL;
}
void *rxthread(void *arg){

struct cShared *sh = (struct cShared *)arg;
//char *msg= (char *)msg1;
mySendingPort *my_send_port1 = sh-> my_send_port;
LossyReceivingPort *my_recv_port1 = sh-> my_recv_port;

  

Packet *pData;
int var2,var1=1;
char *varc1 = "0";
while(1){
    var1=1;
    cout<<"entered while(1) loop"<<endl;
    while(var1){
        cout<<"entered while(var1) loop"<<endl;
        pData = my_recv_port1->receivePacket();
           // cout<<"checking for ack"<<endl;
           if (pData != NULL)
             {
                cout<<"valid data"<<endl;
                var2 = (int)pData->accessHeader()->getOctet(1);
                //*varc1= pData->accessHeader()->getOctet(0);
                var1 = 0;
                cout<<"valid data after header retrieval "<<endl;
             }
      }
      if(pData->accessHeader()->getOctet(0)==REQUEST){         //RESPONDING TO A REQUEST FOR CONTENT

        ifstream myfile;
        //char contentName[8];


        std::stringstream ss;
        string filename1,filename;
        ss << var2;
        filename1= ss.str();

        filename=filename1+".txt";
//        strcat(filename,".txt");
        cout<<"about to read data "<< filename<<endl;


        ifstream file(filename.c_str());
        vector<char>Data;  // used to store all the data from the file.

        //Check if the File is successfully opened or not.
        if(!file.is_open())
        {
           cout<<"\n Could Not open File"<<endl;
        }
   
        //Get the file data
        while (file.good())          // loop while extraction from file is possible
        {
          Data.push_back(file.get());       // get character from file

        }

        file.close();
    //SaveFileAs("3.txt", &Data);




        Packet *my_packet = new Packet();

        PacketHdr *hdr = my_packet->accessHeader();
        hdr->setOctet(RESPONSE,0);
        my_packet->fillPayload( Data.size() , &Data.at(0));

        cout<<"sending data pkt "<<endl;
        //my_send_port1->setACKflag(true);
        my_send_port1->sendPacket(my_packet);

        delete my_packet;
      }else if(pData->accessHeader()->getOctet(0)==RESPONSE){        //I GET DATA
        //PUT DATA IN FILE
        
        
        ofstream myfile;


        std::stringstream ss;
        string filename1,filename;
        ss << var2;
        filename1= ss.str();

        filename=filename1+".txt";

        //filename.c_str()
        myfile.open (filename.c_str());
        myfile << pData->getPayload();
        myfile.close();

        cout<<"entered data response "<< pData->getPayload()<<" in location "<<filename<<endl;

        my_send_port1->setACKflag(true);
        my_send_port1->timer_.stopTimer();        

      }
    }
  

return 0;

}
void *ReceiveProcedure(void *arg){
    
    cout << "Start: Receive procedure." << endl;
    struct RPShared *rp = (struct RPShared *)arg;
    Packet *recvPacket;
    PacketHdr *hdr;
    Packet *data_packet;
    PacketHdr *data_packet_hdr;
    unsigned char packet_id;
    unsigned char content_id;
    unsigned char host_id_requesting;
    while(1){
        
        recvPacket = rp->recv_port->receivePacket();
        hdr = recvPacket->accessHeader();
        packet_id = hdr->getOctet(0);
        if(packet_id == '0'){
            cout<<"\n---------------------------------------------------------"<<endl;
            cout << "Message: Serving a request." << endl;
            int i;
            content_id = hdr->getOctet(1);
            host_id_requesting = hdr->getOctet(2);
            printf("Message: Content ID requested is: %d\n",content_id);
            for(i=0; i<ListOfContents.size(); i++){
                if(ListOfContents.at(i) == content_id){
                    data_packet = new Packet();
                    data_packet_hdr = data_packet->accessHeader();
                    data_packet_hdr->setOctet('1',0);
                    data_packet_hdr->setOctet(content_id,1);
                    data_packet_hdr->setOctet(host_id_requesting,2);
                    //Get the file and store as payload
                    string x = "Content" + to_string((int)content_id) + ".txt";
                    
                    cout<<x<<endl;
                    char *filename = const_cast<char*>(x.c_str());
                    //char *filename="Content4.txt";
                    char buffer[MAX_BUFFER];
                    ifstream f;
                    f.open(filename);
                    int iterator = 0;
                    while(!f.eof()){
                        buffer[iterator] = f.get();
                        iterator++;
                    }
                    f.close();
                    data_packet_hdr->setIntegerInfo(iterator,3);
                    data_packet->fillPayload(iterator,buffer);
                    rp->send_port->sendPacket(data_packet);
                    cout << "Message: Requested content sent." << endl;
                    
                }
                else{
                    cout << "Message: Content not present, drop packet." << endl;
                }
            }
           cout<<"\n---------------------------------------------------------"<<endl; 
        }
        else if(packet_id == '1'){
            // Case when a data packet is received
            cout<<"\n---------------------------------------------------------"<<endl;
            cout << "Message: Data packet received." << endl;
            unsigned char id_requested;
            char* temp;
            
            id_requested = hdr->getOctet(1);
            if(id_requested == ind->content_requested_id){
                cout << "Message:  Data packet is correct." << endl;
                ind->receive_ind = '1';
                temp = recvPacket->getPayload();
                string y = "Content" + to_string((int)id_requested) + ".txt";
                char *fname = const_cast<char*>(y.c_str());
                ofstream f;
                f.open(fname);
                f << temp;
                f.close();
                rp->send_port->setACKflag(true);
                rp->send_port->timer_.stopTimer();
                ListOfContents.push_back(id_requested);
            }
            cout<<"\n---------------------------------------------------------"<<endl;   
            
        }
        else if(packet_id == '2'){
                    
            // Drop packet because hosts don't accept packet announcements
           
        }
        else{
            cout << "Packet ID not proper" << endl;
        }
    }
}