Listing 2: hostdb.cpp

#ifdef WIN32
#pragma warning( disable : 4786 )
#pragma warning( disable : 4503 )
#endif
#include <ctype.h>
#include <string>
#include <stdio.h>
#include "nwayset.h"

class CDNSRecord //A DNS record encapsulator
{
    public:
        inline CDNSRecord(const char *pszName, 
            const char *pszType, const char *pszAddress) 
            : m_strName(pszName), m_strType(pszType),     
              m_strAddress(pszAddress) {};
        string m_strName, m_strType, m_strAddress;       
};

bool DNSNameCompare(const CDNSRecord &obj1, 
         const CDNSRecord &obj2)
    {return obj1.m_strName < obj2.m_strName;}
bool DNSAddressCompare(const CDNSRecord &obj1, 
         const CDNSRecord &obj2)
    {return obj1.m_strAddress < obj2.m_strAddress;}

//parse lines from an nslookup ls > file
const char *GetNextWord(char ** ppsz) 
{
    char *psz=*ppsz;
    if(!psz) return NULL;
    while(*psz && iswspace(*psz)) psz++;
    if(!*psz) return NULL;
    char *pszResult=psz;
    while(*psz && !iswspace(*psz)) psz++;
    if(*psz) { *psz=0; psz++;}
    *ppsz=psz;
    return pszResult;
}

//Trim left and right white space from a string
int alltrim(char *psz) 
{
   int iLength=strlen(psz);
   for(int iCount=iLength-1;iCount>=0 && 
       isspace(psz[iCount]); iCount--);
   iLength=iCount+1;
   psz[iLength]=0;
   for(iCount=0;psz[iCount]&&isspace(psz[iCount]);iCount++);
   if(iCount)
   {
      strcpy(psz,psz+iCount);
      iLength-=iCount;
   }      
   return iLength;
}

void main(int argc, char *argv[])
{
    char szLine[100];
    
    if(argc!=2)     return;
        
    //create our n-way set and insert our indexes
    nwayset<CDNSRecord> nsDNSLookup;
    
    nsDNSLookup.index_insert(DNSNameCompare);
    nsDNSLookup.index_insert(DNSAddressCompare);
    
    //process our file
    FILE *pFile=fopen(argv[1], "r");
    while(fgets(szLine, 99, pFile))
    {
        alltrim(szLine);
        if(ispunct(szLine[0])) continue;
        char *pLine=szLine;
        const char *pszName, *pszType, *pszAddress;
        if((pszName=GetNextWord(&pLine))&&
               (pszType=GetNextWord(&pLine))&&
               (pszAddress=GetNextWord(&pLine)))
            nsDNSLookup.insert(
                CDNSRecord(pszName, pszType, pszAddress));
    }
    fclose(pFile);

    printf("Processed %d records.\n", nsDNSLookup.size());

    for(;;) 
    {
        //grab an address/hostname to look up
        printf("Type in query string> ");
        gets(szLine);
        if(alltrim(szLine)<=0)
            break;
        //search all indexes
        CDNSRecord objSearch(szLine,"",szLine);
        nwayset<CDNSRecord>::const_iterator it =
            nsDNSLookup.find(objSearch);
        if(it!=nsDNSLookup.end())
            printf("Hostname: %s\nAddress: %s\n",
         (*it).m_strName.c_str(),
         (*it).m_strAddress.c_str());
    }
}