#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define CHARS 27
#define MAX 100
int getIndex(char c)
{
return (c == '.') ? 26 : (c - 'a');
}
char getCharFromIndex(int i)
{
return (i == 26) ? '.' : ('a' + i);
}
struct trieNode
{
bool isLeaf;
char *ipAdd;
struct trieNode *child[CHARS];
};
struct trieNode *newTrieNode(void)
{
struct trieNode *newNode = new trieNode;
newNode->isLeaf = false;
newNode->ipAdd = NULL;
for (int i = 0; i<CHARS; i++)
newNode->child[i] = NULL;
return newNode;
}
void insert(struct trieNode *root, char *URL, char *ipAdd)
{
int len = strlen(URL);
struct trieNode *pCrawl = root;
for (int level = 0; level<len; level++)
{
int index = getIndex(URL[level]);
if (!pCrawl->child[index])
pCrawl->child[index] = newTrieNode();
pCrawl = pCrawl->child[index];
}
pCrawl->isLeaf = true;
pCrawl->ipAdd = new char[strlen(ipAdd) + 1];
strcpy(pCrawl->ipAdd, ipAdd);
}
char *searchDNSCache(struct trieNode *root, char *URL)
{
struct trieNode *pCrawl = root;
int len = strlen(URL);
for (int level = 0; level<len; level++)
{
int index = getIndex(URL[level]);
if (!pCrawl->child[index])
return NULL;
pCrawl = pCrawl->child[index];
}
if (pCrawl != NULL && pCrawl->isLeaf)
return pCrawl->ipAdd;
return NULL;
}
int main()
{
char URL[][50] = { "www.samsung.com", "www.samsung.net",
"www.google.in"
};
char ipAdd[][MAX] = { "107.108.11.123", "107.109.123.255",
"74.125.200.106"
};
int n = sizeof(URL) / sizeof(URL[0]);
struct trieNode *root = newTrieNode();
for (int i = 0; i<n; i++)
insert(root, URL[i], ipAdd[i]);
char url[] = "www.samsung.com";
char *res_ip = searchDNSCache(root, url);
if (res_ip != NULL)
printf("Forward DNS look up resolved in cache:\n%s --> %s",
url, res_ip);
else
printf("Forward DNS look up not resolved in cache ");
return 0;
}