Exemple #1
0
int main(int argc, char * argv[])
{
    int counter1 = 0;
    int hashValue;
    int sizeOfList = 102;
    int * sizePtr = &sizeOfList;
    bucket * root;
    //bucket * conductor;
    char ** wordList;
    char * toBeHashed;
    char userInput[BUFSIZE];

    FILE* inputFile;
    
    if (argc != 2)
    {
        printf("Please input a file name and nothing else.\n");
        exit(0);
    }

    inputFile = fopen(argv[1], "r");
    if (inputFile == NULL)
    {
        printf("The file '%s' does not exist.  Quiting.\n", argv[1]);
        exit(0);
    }

    wordList = readFile(inputFile);
    fclose(inputFile);

    root = initLinkedList(sizePtr);    

    if(root == NULL)
    {
        printf("Error creating linked list, quiting...\n");
        exit(0);
    }

    while (wordList[counter1] != NULL)
    {
        hashValue = findHash(wordList[counter1]);
        addHash(hashValue, wordList[counter1], root);
        counter1++;
    }
    free(wordList);

    printf("List successfully hashed! Ready for queries: ");
    while (1==1)
    {
        fgets(userInput, BUFSIZE, stdin);
        toBeHashed = malloc(strlen(userInput)+1);
        strcpy(toBeHashed, userInput);
        hashValue = findHash(toBeHashed);

        queryDatabase(hashValue, root, toBeHashed);
        printf("Ready for queries: ");
    }

    return 0;
}
//----------------------------------------------------------------------------
Callback *CallbackManager::getCallback( string actionString)
{
    XTRACE();
    Callback * cb = findHash( actionString, _actionMap);
    if( !cb)
    {
        LOG_ERROR << "Unable to find callback for " << actionString << endl;
        string dummyAction = "TertiaryFire";
        cb = findHash( dummyAction, _actionMap);
    }
    return cb;
}
Exemple #3
0
/*	================== addAirport =================
 This function adds another element of data into
 both the tree and hash table, through the user's
 input from keyboard.
 Pre		pHeader - pointer to HEAD structure
 Post
 Return	true if success
 false if fails
 */
bool addAirport (HEAD* pHeader)
{
	//	Local Declarations
    bool result = false;
    DATA tempAirport;
    DATA* newAirport = NULL;
    char tempCode [28];
    char tempName [128];
    int i;
    
	
	printf ("Enter airport code: ");
	scanf (" %s", tempCode);
    
    if (strlen(tempCode) != 3) {
        printf("Your airport code has to have 3 characters\n");
        return result;
    }
	
    for (i = 0; i<strlen(tempCode); i++) {
        tempCode[i] = toupper(tempCode[i]);
    }
    
    strcpy(tempAirport.arpCode, tempCode);
    newAirport = findHash(pHeader->pHash, &tempAirport);
    if (newAirport == NULL)
    {
        if (!(newAirport = (DATA*) malloc(sizeof(DATA)))) {
            printf("Error allocating new airport\n");
            exit(100);
        }
        strcpy(newAirport->arpCode, tempCode);
        printf("Enter airport city: ");
        scanf(" %[^\n]", tempName);
        newAirport->city = (char*) calloc(strlen(tempName) + 1, sizeof(char));
        strcpy(newAirport->city, tempName);
        
        printf("Enter airport latitude: ");
        while(!(scanf("%f", &newAirport->latitude)))
        {
            printf("Invalid input, please try entering the latitude again: ");
            while(getchar() != '\n');
        }
        printf("Enter airport longitude: ");
        while(!(scanf("%f", &newAirport->longitude)))
        {
            printf("Invalid input, please try entering the longitude again: ");
            while(getchar() != '\n');
        }
        
        insertHash(pHeader->pHash, newAirport);
        BST_Insert(pHeader->pTree, newAirport);
        result = true;
    }
    else{
        printf("This airport already exists\n");
        processScreen(newAirport);
    }
    return result;
}	// addAirport
Exemple #4
0
// (new ['flg|num] ['typ ['any ..]]) -> obj
any doNew(any ex) {
   any x, y, *h;
   cell c1, c2;

   x = cdr(ex);
   if (isCell(y = EVAL(car(x))))
      Push(c1, consSym(y,Nil));
   else {
      if (isNil(y))
         data(c1) = consSym(Nil,Nil);
      else {
         y = newId(ex, isNum(y)? (int)unDig(y)/2 : 1);
         if (data(c1) = findHash(y, h = Extern + ehash(y)))
            tail(data(c1)) = y;
         else
            *h = cons(data(c1) = consSym(Nil,y), *h);
         mkExt(data(c1));
      }
      Save(c1);
      x = cdr(x),  val(data(c1)) = EVAL(car(x));
   }
   TheKey = T,  TheCls = NULL;
   if (y = method(data(c1)))
      evMethod(data(c1), y, cdr(x));
   else {
      Push(c2, Nil);
      while (isCell(x = cdr(x))) {
         data(c2) = EVAL(car(x)),  x = cdr(x);
         put(data(c1), data(c2), EVAL(car(x)));
      }
   }
   return Pop(c1);
}
Exemple #5
0
void testHash ( const char * name )
{
  HashInfo * pInfo = findHash(name);

  if(pInfo == NULL)
  {
    printf("Invalid hash '%s' specified\n",name);
    return;
  }
  else
  {
    g_hashUnderTest = pInfo;

    if(pInfo->hashbits == 32)
    {
      test<uint32_t>( VerifyHash, pInfo );
    }
    else if(pInfo->hashbits == 64)
    {
      test<uint64_t>( pInfo->hash, pInfo );
    }
    else if(pInfo->hashbits == 128)
    {
      test<uint128_t>( pInfo->hash, pInfo );
    }
    else if(pInfo->hashbits == 256)
    {
      test<uint256_t>( pInfo->hash, pInfo );
    }
    else
    {
      printf("Invalid hash bit width %d for hash '%s'",pInfo->hashbits,pInfo->name);
    }
  }
}
Exemple #6
0
int main() {
    hashTable ht;
    asserthashInit(&ht);
    addHash(&ht, 816, 620);
    int v = findHash(&ht, 816);
    printf("%d\n", v);
}
ParticleGroup *ParticleGroupManager::getParticleGroup( const string &groupName)
{
    XTRACE();
    ParticleGroup * pg = findHash( groupName, _particleGroupMap);
    if( !pg)
    {
        LOG_ERROR << "Unable to find particle group " << groupName << endl;
    }
    return pg;
}
Exemple #8
0
    Model *getModel( std::string modelName)
    {
        Model *model = findHash( modelName, _modelMap);
        if( !model)
        {
	    model = load( modelName);
	    if( !model)
	    {
		LOG_ERROR << "Unable to find model " << modelName << "\n";
		return 0;
	    }
	    _modelMap[ modelName] = model;
        }
        return model;
    }
Exemple #9
0
int updateHash(int id, char *cost)
{
        //First save the given node's updport and hostname
        struct nodeInfo *s;
        s = findHash(id);
        
        char tempUdpport[15];
        strcpy(tempUdpport, s->udpPort);
        char temphostName[15];
        strcpy(temphostName, s->hostName);
        int next = s->nextHop;
        
        int oldCost, newCost;
        oldCost = atoi(s->cost);
        newCost = atoi(cost);
        //Delete entry for the the particular node
        if( oldCost > newCost )
        {
		    HASH_DEL(table, s);
		    
		    //Create a new entry with updated info
		    struct nodeInfo *temp = NULL;
		    temp = (struct nodeInfo*)malloc(sizeof(struct nodeInfo));
		    temp->ID = id;
		    strcpy(temp->udpPort, tempUdpport);
		    strcpy(temp->hostName, temphostName);
		    strcpy(temp->cost, cost);
		    temp->nextHop = next;
		    HASH_ADD_INT(table, ID, temp);
		    findHash(id);					//debug message
		}
		else
			printf("Old cost is smallest\n");
			
        return 1;
}
Exemple #10
0
//----------------------------------------------------------------------------
void Input::bind( Trigger &trigger, Callback *callback)
{
    XTRACE();
    Callback * cb = findHash( trigger, _callbackMap);
    if( cb)
    {
        LOG_INFO << "Removing old binding" << endl;
        //remove previous callback...
        _callbackMap.erase( trigger);
        //delete cb;
        LOG_INFO << "DELETE SUCCESSFULL" << endl;
    }

    LOG_INFO << "Creating binding for " << callback->getActionName()
             << " - " << trigger.type << ":" << trigger.data1 << endl;
    _callbackMap[ trigger] = callback;
}
Exemple #11
0
int readStr(FILE* file, STRING** table)
{
    int chr = 0;
    long addr = 0;
    unsigned long long hash = 0;
    int i = 0;

    addr = ftell(file);

    while(EOF != (chr = fgetc(file)))
    {
        if(chr == '\n' || chr == 0)
        {
            break;
        }

        hash += hash * 255 + chr;
    }

    i = findHash(hash, table);

    if(table[i])
    {
        table[i]->freq++;
    }else
    {
        table[i] = (STRING*)malloc(sizeof(STRING));
        checkMem(table[i]);
        table[i]->addr = addr;
        table[i]->freq = 1;
        table[i]->hash_ = hash;
    }

    table[i + 1] = NULL;

    return ((chr == EOF) ? 0 : 1);
}
Exemple #12
0
void buildCSp ( zeroCircuit *node, cs *arrayC, hashTable *namTab, int kPos )
{
	int posn1;
	int posn2;
	double tmp;

	struct linear_element *element;

	element = node->linElement;


	switch ( node->type )
	{
	case 0:
		switch( node->linElement->element )
		{
		case 4:
			if ( ( strcmp( node->linElement->connectors[0], "0\0" ) ) && ( strcmp( node->linElement->connectors[1], "0\0" ) ) )
			{
				//posn1 = findPlace ( node->linElement->connectors[0], &nodes );
				//posn2 = findPlace ( node->linElement->connectors[1], &nodes );

				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );

				tmp = (-1.0) * node->linElement->value;
				cs_entry(arrayC,posn1,posn2,tmp);
				cs_entry(arrayC,posn2,posn1,tmp);

			}

			if ( strcmp( node->linElement->connectors[0], "0\0" ) )
			{
				//posn1 = findPlace ( node->linElement->connectors[0], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				tmp = node->linElement->value;
				cs_entry(arrayC,posn1,posn1,tmp);
			}

			if ( strcmp( node->linElement->connectors[1], "0\0" ) )
			{
				//posn2 = findPlace ( node->linElement->connectors[1], &nodes );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );
				tmp = node->linElement->value;
				cs_entry(arrayC,posn2,posn2,tmp);
			}

			break;

		case 5:

			tmp = -node->linElement->value;
			cs_entry(arrayC, kPos + namTab->currPos - 1, kPos + namTab->currPos - 1, tmp);
			break;
		}
		break;

	case 1:
		//irrelevant
		break;
	}

}
Exemple #13
0
/*	================== getOption =================
 This function reads in the user's desired chose
 of operation. Calls upon other functions to
 perform the procedure.
 Pre		pHeader - pointer to HEAD structure
 Post
 Return
 */
void getOption (HEAD* pHeader)
{
	//	Local Declarations
    char command;
    DATA target;
    DATA* airport = NULL;
	int i;
    
	//	Statements
    while ((command = menu()) != 'Q') {
        switch (command)
        {
            case 'A':
                if (addAirport(pHeader))
                {
                    while (checkHash(pHeader->pHash) == 1) {
                        pHeader->pHash = upsizeHash(pHeader->pHash);
                    }
					printf ("\n Succesfully added data.\n\n");
                }
                break;
            case 'D':
                printf("Enter the airport code: ");
                scanf(" %s", target.arpCode);
                
				if (deleteHash (pHeader, target))
                {
                    while (checkHash(pHeader->pHash) == -1) {
                        pHeader->pHash = downsizeHash(pHeader->pHash);
                    }
					printf ("\n Succesfully deleted data.\n\n");
                }
                
                break;
            case 'F':
                printf("Enter the airport code: ");
                scanf(" %s", target.arpCode);
				// fix sensitive input cases
				for (i = 0; i < strlen(target.arpCode); i++) {
					target.arpCode[i] = toupper(target.arpCode[i]);
				}
                airport = findHash(pHeader->pHash, &target);
                if (airport != NULL) {
                    processScreen(airport);
                }
                else printf("No airport exists\n");
                
                break;
            case 'L':
                printHash(pHeader->pHash);
                break;
            case 'K':
                BST_Traverse(pHeader->pTree, processScreen);
                break;
            case 'P':
                printTree(pHeader->pTree->root, 0);
				printf("\n");
                break;
            case 'W':
				outputFile (pHeader->pHash);
                break;
            case 'E':
				efficiency(pHeader->pHash);
                break;
			case 'H':
				pHeader->pHash = hashDemo(pHeader->pHash);
				break;
            default:
                printf("Invalid choice. Choose again\n");
                break;
        }
    }
    return;
}	// getOption
Exemple #14
0
static int bitVectorTraversePlausibility(unsigned int **bitVectors, nodeptr p, int numsp, unsigned int vectorLength, hashtable *h,
					 int *countBranches, int firstTaxon, tree *tr, boolean multifurcating)
{

  /* trivial bipartition */

  if(isTip(p->number, numsp))
    return 0;
  else
    {
      int 
	found = 0;

      nodeptr 
	q = p->next;          

      /* recursively descend into the tree and get the bips of all subtrees first */

      do 
	{
	  found = found + bitVectorTraversePlausibility(bitVectors, q->back, numsp, vectorLength, h, countBranches, firstTaxon, tr, multifurcating);
	  q = q->next;
	}
      while(q != p);
           
      /* compute the bipartition induced by the current branch p, p->back,
	 here we invoke two different functions, depending on whether we are dealing with 
	 a multi-furcating or bifurcating tree.
      */

      if(multifurcating)
	newviewBipartitionsMultifurcating(bitVectors, p, numsp, vectorLength);
      else
	newviewBipartitions(bitVectors, p, numsp, vectorLength);
      
      assert(p->x);      

      /* if p->back does not lead to a tip this is an inner branch that induces a non-trivial bipartition.
	 in this case we need to lookup if the induced bipartition is already contained in the hash table 
      */

      if(!(isTip(p->back->number, numsp)))
	{	
	  /* this is the bit vector to insert into the hash table */
	  unsigned int 
	    *toInsert = bitVectors[p->number];
	  
	  /* compute the hash number on that bit vector */
	  hashNumberType 
	    position = oat_hash((unsigned char *)toInsert, sizeof(unsigned int) * vectorLength) % h->tableSize;	 	 

	  /* each bipartition can be stored in two forms (the two bit-wise complements
	     we always canonically store that version of the bit-vector that does not contain the 
	     first taxon of the small tree, we use an assertion to make sure that all is correct */

	  assert(!(toInsert[(firstTaxon - 1) / MASK_LENGTH] & mask32[(firstTaxon - 1) % MASK_LENGTH]));	 
	  	      
	  /* increment the branch counter to assure that all inner branches are traversed */
	  
	  *countBranches =  *countBranches + 1;	
	  	 	
	  /* now look up this bipartition in the hash table, If it is present the number of 
	     shared bipartitions between the small and the big tree is incremented by 1 */
	   
	  found = found + findHash(toInsert, h, vectorLength, position);	
	}
      return found;
    }
}
Exemple #15
0
//----------------------------------------------------------------------------
bool Input::update( void)
{
//    XTRACE();
    bool isDown;
    Trigger trigger;

    static float nextTime = Timer::getTime()+0.5f;
    float thisTime = Timer::getTime();
    if( thisTime > nextTime)
    {
        updateMouseSettings();
        nextTime = thisTime+0.5f;
    }

    _valDX = 0.0f;
    _valDY = 0.0f;

    while( tryGetTrigger( trigger, isDown))
    {
        if( trigger.type == eUnknownTrigger)
        {
            //for unkown trigger we don't need to do a lookup
            continue;
        }

        if( _interceptor)
        {
            //feed trigger to interceptor instead of normal callback mechanism
            _interceptor->input( trigger, isDown);
            continue;
        }

        if( !_bindMode)
        {
            //find callback for this trigger
            //i.e. the action bound to this key
            Callback * cb = findHash( trigger, _callbackMap);
            if( cb)
            {
//                LOG_INFO << "Callback for [" << cb->getActionName() << "]" << endl;
                cb->performAction( trigger, isDown);
            }
        }
        else if( _callback && (trigger.type!=eMotionTrigger))
        {
            //Note: motion triggers can't be bound

            //we are in bind-mode, so bind this trigger to callback
            bind( trigger, _callback);
            //go back to normal mode
            _bindMode = false;
        }
        else if( !_callback)
        {
            LOG_ERROR << "Input is in bind mode, but callback is 0" << endl;
            _bindMode = false;
        }
    }
    _valDX = feedbackFilter( _valDX, _dampVal, _memoryDX);
    _valDY = feedbackFilter( _valDY, _dampVal, _memoryDY);

    if( (fabs(_valDX)>1.0e-10) || (fabs(_valDY)>1.0e-10))
    {
        trigger.type = eMotionTrigger;
        trigger.fData1 = _valDX;
        trigger.fData2 = _valDY;

        if( _interceptor)
        {
            //feed trigger to interceptor instead of normal callback mechanism
            _interceptor->input( trigger, true);
        }
        else
        {
            Callback * cb = findHash( trigger, _callbackMap);
            if( cb)
            {
//                LOG_INFO << "Callback for [" << cb->getActionName() << "]" << endl;
                cb->performAction( trigger, isDown);
            }
        }
    }

    return true;
}
Exemple #16
0
void addElementStampSparse( zeroCircuit *node, mnaSpSystem *system, cs *arrayA, hashTable *namTab, int row, int kPos)
{
	int posn1;
	int posn2;
	double tmp;

	struct linear_element *element;

	element = node->linElement;


	switch ( node->type )
	{
	case 0:
		switch( node->linElement->element )
		{
		case 1:

			if ( ( strcmp( node->linElement->connectors[0], "0\0" ) ) && ( strcmp( node->linElement->connectors[1], "0\0" ) ) )
			{
				//posn1 = findPlace ( node->linElement->connectors[0], &nodes );
				//posn2 = findPlace ( node->linElement->connectors[1], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );

				tmp = (-1.0) * ( 1.0 / node->linElement->value);
				cs_entry(arrayA,posn1,posn2,tmp);
				cs_entry(arrayA,posn2,posn1,tmp);

			}

			if ( strcmp( node->linElement->connectors[0], "0\0" ) )
			{
				//posn1 = findPlace ( node->linElement->connectors[0], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				tmp = ( 1.0 / node->linElement->value );
				cs_entry(arrayA,posn1,posn1,tmp);
			}

			if ( strcmp( node->linElement->connectors[1], "0\0" ) )
			{
				//posn2 = findPlace ( node->linElement->connectors[1], &nodes );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );
				tmp = ( 1.0 / node->linElement->value );
				cs_entry(arrayA,posn2,posn2,tmp);
			}

			break;
		case 3:

			if ( strcmp( node->linElement->connectors[0], "0\0" ) )
			{
				//posn1 = findPlace ( node->linElement->connectors[0], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				system->vector_B[posn1] += (-1.0) * element->value;
			}

			if ( strcmp( node->linElement->connectors[1], "0\0" ) )
			{
				//posn2 = findPlace ( node->linElement->connectors[1], &nodes );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );
				system->vector_B[posn2] += element->value;
			}

			break;
		case 2: //case 2same as 5
		case 5:
			element->k = kPos;
			if (element->element == 2)
			{
				system->vector_B[ namTab->currPos -1 + kPos ] += element->value;

				//printf ( "bug ib B: %f\n", element->value );
			}


			if ( ( strcmp( node->linElement->connectors[0], "0\0" ) ) && ( strcmp( node->linElement->connectors[1], "0\0" ) ) )
			{
				//posn1 = findPlace ( element->connectors[0], &nodes );
				//posn2 = findPlace ( element->connectors[1], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );

				cs_entry(arrayA,kPos + namTab->currPos -1,posn1,1.0);
				cs_entry(arrayA,kPos + namTab->currPos -1,posn2,-1.0);

				cs_entry(arrayA,posn1,kPos + namTab->currPos -1,1.0);
				cs_entry(arrayA,posn2,kPos + namTab->currPos -1,-1.0);
				break;

			}

			if ( strcmp( node->linElement->connectors[0], "0\0" ) )
			{
				//posn2 = findPlace ( element->connectors[1], &nodes );
				posn2 = findHash ( namTab, node->linElement->connectors[1] );

				cs_entry(arrayA,kPos + namTab->currPos -1,posn2,-1.0);
				cs_entry(arrayA,posn2,kPos + namTab->currPos -1,-1.0);

				break;
			}

			if ( strcmp( node->linElement->connectors[1], "0\0" ) )
			{
				//posn1 = findPlace ( element->connectors[0], &nodes );
				posn1 = findHash ( namTab, node->linElement->connectors[0] );

				cs_entry(arrayA,kPos + namTab->currPos -1,posn1,1.0);
				cs_entry(arrayA,posn1,kPos + namTab->currPos -1,1.0);

			}

			break;
		}

		break;
	case 1:
		//irrelevant
		break;
	}

}
Exemple #17
0
int saveHash(char *buf, int next)
{
        
        printf("BUFFAH! = %s\n", buf);
        
        char *space = " ";
        struct nodeInfo *temp=NULL;
        struct nodeInfo *sendPort;
		char message[15];
		strcpy(message, strtok (buf, space ));
        int sendPortCost, tempCost;        
        char *temptempID = strtok( '\0' , space );      
        int tempID = atoi(temptempID );
        //HASH_FIND_INT(table, &tempID, temp);   /* id already in the hash? */
        
        
        if(temp == NULL)
        {
                temp = (struct nodeInfo*)malloc(sizeof(struct nodeInfo));
                sendPort = temp;
                //ENTRY item;   
                char *space = " " ;
                temp->ID = tempID;
                char *nline = "\n";
                strcpy( temp->hostName , strtok( '\0' ,space ) );
                strcpy(temp->udpPort , strtok( '\0' ,space ) );                         
                     
                if( strcmp(message, "NEW") == 0 || strcmp(message, "UPDATE") == 0)
				{
					strcpy (temp->cost ,  strtok( '\0' , space));
					tempCost = atoi(temp->cost);
					
					
					
					char *tempn = strtok('\0',space);
					printf(" Temp (next) is : %s\n", tempn); 	
					next = atoi(tempn);  
					printf("next is : %d \n", next); 		//debug message    
					temp->nextHop = next;
					
					while(sendPort->ID != sendPort->nextHop)
					{
		    			sendPort = findHash(sendPort->nextHop);
		    			sendPortCost = atoi(sendPort->cost);
		    			tempCost += sendPortCost;			 		
		    		}
					itoa(tempCost, temp->cost);
				}
				else
				{
					strcpy (temp->cost ,  strtok( '\0' , nline));
					temp->nextHop = next;
				}
				
						
				
		    	
        		
                //item.key =  strdup(temp.ID);
                printf(" Temp ID = %d\n", temp->ID);
                //item.data = &temp;
                printf( " Cost is : %s \n" , temp->cost );
        


                //store in Hash Table
                pthread_mutex_lock(&lock);
                HASH_ADD_INT(table, ID, temp);
                findHash(tempID);
                pthread_mutex_unlock(&lock);
                return 1;
        }	//loop through hash table

        
        else
                return 0;
        
}
Exemple #18
0
void *udpConnection(void *args)
{
        
  	//	sleep(5);
        //TCP communication w/ Mr. Manager
        struct threadArgs *thrdArg = (struct threadArgs *)args;
        int sockfd = thrdArg->fd;
        char addr[15];
        strcpy(addr, thrdArg->adr);
        char host[15];
        strcpy(host, thrdArg->hst);
        
        strcpy(listenOn , thrdArg->listen);
        
        //UDP listen sockfd_udp
        int sockfd_udp;
        struct addrinfo hints_udp, *servinfo_udp, *p_udp;
        struct sockaddr_storage their_addr;
        int MAXBUFLEN = 100;
        char listenBuf[MAXBUFLEN],sendBuf[MAXBUFLEN];
        socklen_t addr_len;
        char s_udp[INET6_ADDRSTRLEN];
        int rv, numbytes;

        memset(&hints_udp, 0, sizeof hints_udp);
        hints_udp.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
        hints_udp.ai_socktype = SOCK_DGRAM;
        hints_udp.ai_flags = AI_PASSIVE; // use my IP

        if ((rv = getaddrinfo(NULL, listenOn , &hints_udp, &servinfo_udp)) != 0) {
                fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
        }

        // loop through all the results and bind to the first we can
        for(p_udp = servinfo_udp; p_udp != NULL; p_udp = p_udp->ai_next) {
                if ((sockfd_udp = socket(p_udp->ai_family, p_udp->ai_socktype,
                                p_udp->ai_protocol)) == -1) {
                        perror("listener: socket");
                        continue;
                }

                if (bind(sockfd_udp, p_udp->ai_addr, p_udp->ai_addrlen) == -1) {
                        close(sockfd_udp);
                        perror("listener: bind");
                        continue;
                }

                break;
        }

        if (p_udp == NULL) {
                fprintf(stderr, "listener: failed to bind socket\n");
                
        }

        freeaddrinfo(servinfo_udp);
////////////////////UDP THREAD/////////////////////////////////////////////////////////


		while(1)
			{

		    //recieve message/packet from mr. manager to fwd
		    //udp recieve 
		    
		    printf("listener: waiting to recvfrom...\n");

			//setup select to wait for connection ack
				  struct timeval tv;
			 fd_set readfds;

			 tv.tv_sec = 2;
			 tv.tv_usec = 500000;

			 FD_ZERO(&readfds);
			 FD_SET(sockfd_udp, &readfds);

			select(sockfd_udp+1, &readfds, NULL, NULL, &tv);
                
         if (FD_ISSET(sockfd_udp, &readfds))
			{
		    addr_len = sizeof their_addr;
		    if ((numbytes = recvfrom(sockfd_udp, listenBuf, MAXBUFLEN-1 , 0,
		            (struct sockaddr *)&their_addr, &addr_len)) == -1) {
		            perror("recvfrom");
		            exit(1);
		    }
			}


		    if (numbytes == 0)
		    	continue;
		    
		    char sendBuf[100];
		    int i = 0;
		    //debug messages
		    printf("listener: got packet from %s\n",
		    inet_ntop(their_addr.ss_family,
		    get_in_addr((struct sockaddr *)&their_addr),
		                                    s_udp, sizeof s_udp));  
		    printf("listener: packet is %d bytes long\n", numbytes);
		    listenBuf[numbytes] = '\0';
		    
		    
		    //Copy listenBuf to sendBuf
		    memcpy ( (void *) sendBuf, (void *) listenBuf, numbytes);
		    
		    sendBuf[numbytes] = '\0';
		    
		 //   strcpy(sendBuf, listenBuf);
		    printf("listener: packet contains \"%s\"\n", listenBuf);	//debug message
		    printf("sendBuf contains : %s \n", sendBuf);				//debug message
		    

		    
		    
		    char type = listenBuf[0];
		    if((int)type == 1)
		    {
		            uint send_id = (int) ( listenBuf[2] |  (listenBuf[1] << 8) );
		            printf("send id is : %d\n", send_id);	//debug message


		            char data[50];
		            int k,l;
		            for(k =3,l=0 ; k< numbytes; k++, l++)
		            {
		                    data[l] = listenBuf[k] ; 
		                    printf("%c\n" , data[l]);       //debug message
		            }
		            data[l] = '\0';
		            
		            
		            printf("atoi of addr: %s\n", addr);		//debug message
		            if((int)send_id == atoi(addr))
		            //Message arrived at destination
		            {
		             		printf("LOG DICKS\n");
		                    sendLog(send_id, data, 1, sockfd);
		            }
		            else
		            {
		            
		            
		            	
		            	
		            	struct nodeInfo * sendPort = findHash(send_id);
		    			
		    			//Send only if ID of next hop == ID of send_id
		    			//Else lookup info for next hop
		    			while(sendPort->ID != sendPort->nextHop)
		    				sendPort = findHash(sendPort->nextHop);		//if(sendPort->ID != sendPort->nextHop)
		    				
		    			
		    			
							char dstPort[15];
							for(k = 0; k < 15; k++ )
						   		dstPort[k] = sendPort->udpPort[k];
		                   
							//UDP forward
							sendLog(sendPort->ID, data, 0, sockfd);
							
							

		                                            
                    		//Get external ip address
							struct ifaddrs * ifAddrStruct=NULL;
							struct ifaddrs * ifa=NULL;
							void * tmpAddrPtr=NULL;
							char addressBuffer[INET_ADDRSTRLEN];

							getifaddrs(&ifAddrStruct);

							for (ifa = ifAddrStruct; ifa != NULL; ifa = ifa->ifa_next) {
								if (ifa ->ifa_addr->sa_family==AF_INET) { // check it is IP4
									// is a valid IP4 Address
									tmpAddrPtr=&((struct sockaddr_in *)ifa->ifa_addr)->sin_addr;
								
									inet_ntop(AF_INET, tmpAddrPtr, addressBuffer, INET_ADDRSTRLEN);
									//printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); 
								} 
								else if (ifa->ifa_addr->sa_family==AF_INET6) { // check it is IP6
									// is a valid IP6 Address
									tmpAddrPtr=&((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_addr;
									char addressBuffer[INET6_ADDRSTRLEN];
									inet_ntop(AF_INET6, tmpAddrPtr, addressBuffer, INET6_ADDRSTRLEN);
									//printf("%s IP Address %s\n", ifa->ifa_name, addressBuffer); 
								} 
							}
							if (ifAddrStruct!=NULL) freeifaddrs(ifAddrStruct);                       
		                    
		                    
		                     
		                    //UDP send sockfd_send
		                    struct addrinfo hints, *p;    
		                    int sockfd_send;
		                    struct addrinfo *servinfo_send;
		                    memset(&hints, 0, sizeof hints);
		                    hints.ai_family = AF_UNSPEC;
		                    hints.ai_socktype = SOCK_DGRAM;

		                    if ((rv = getaddrinfo(addressBuffer, dstPort, &hints, &servinfo_send)) != 0) {
		                      fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
		                     
		                    }

		                    // loop through all the results and make a socket
		                    for(p = servinfo_send; p != NULL; p = p->ai_next) {
		                      if ((sockfd_send = socket(p->ai_family, p->ai_socktype,
		                                             p->ai_protocol)) == -1) {
		                                    perror("talker: socket");
		                                    continue;
		                      }
		                      break;
		                   }

		                    if (p == NULL) {
		                      fprintf(stderr, "talker: failed to bind socket\n");
		                    
		                    }
		                    
		                    for(k = 0 ; k<numbytes; k++)
		            			printf("%c\n" , listenBuf[k]);
		                    
							printf("listenBuf length is: %d\n", strlen(listenBuf)); 	//debug message
		                    if ((numbytes = sendto(sockfd_send, listenBuf, numbytes, 0,
		                                             p->ai_addr, p->ai_addrlen)) == -1) {
		                              perror("talker: sendto");
		                              exit(1);
		                     }
		                    
		                     freeaddrinfo(servinfo_send);

		                     printf("talker: sent %d bytes to %s\n", numbytes, dstPort);
		                     close(sockfd_send);
		    
		            }
		    }       
		    else
		    //if((int)type == 0)
		    {
		    	char *space = " ";
		    	char message[10];
		    	char temp[100];
		    	char propogate[100];
		    	int identify, lookup;
				char tempID[10];
				char cst[10];
				char templookup[10];
				char savehsh[100];
				
		    	strcpy(temp, listenBuf);	
		    	//strcpy(propogate, listenBuf);	    	
		    	strcpy(savehsh, listenBuf);
				strcpy(message, strtok(listenBuf, space));
				if(strcmp(message, "ACK") != 0)
				{
					strtok(temp, space);
					strcpy(tempID, strtok('\0', space));
					strtok('\0', space);
					strtok('\0', space);
					strcpy(cst, strtok('\0', space));	
					strcpy(templookup, strtok('\0', space));
				
					if(strcmp(message, "NEW") == 0)
						saveHash(savehsh, 0);
					else if(strcmp(message, "UPDATE") == 0)
					{
						identify = atoi(tempID);
						updateHash(identify, cst);
					}
					//Send the ack
					lookup = atoi(templookup);
					struct nodeInfo *look = findHash(lookup);
				
					sendMessageHelper("ACK ", look->udpPort);
				
				}
				else
					ackflag = 1;
			
				//propagateControl(propogate);	
				

		    }
		    
		}		    

        close(sockfd_udp);
        return NULL;
} 
Exemple #19
0
void insertTable(int key, int buckets, struct Node ** tablePtr)
{
	int spot = findHash(key, buckets);
	insertNode(key, &tablePtr[spot]);
}