Thursday, June 02, 2005

WHOIS Database query using C# winforms applications

Recently i was trying to trace ip address of web clients to valid some query requested from me. I came to a scenario where i had a bunch of ips and times but whether the ips belonged to the same isp or not.

so i started looking up the net for some webservices (well from work everything other than port 80 is blocked) and i found some... they either charged money or where not returning any useful information.

so finally after looking around for an hour or two i set to write it myself. looked up some website that did whois query.... saw one which took a querystring parameter of ip address as string.

anyways it did work.. i did not modify it to work with private ip address. the data passed for private ip address ranges ie 10.x.x.x and 192.x.x.x range etc are different and the code can be modified.. help yourself i you need to do something like that. Here's the code.





if(this.txtIPAddress.Text != null && this.txtIPAddress.Text != "")
{
this.btnLookup.Enabled = false;

string LookupURL = "http://www.dnsstuff.com/tools/whois.ch?ip=";

NetworkCredential nc = new NetworkCredential("uname", "pass", "domain");


WebProxy wp = new WebProxy("http://networkproxyserver:80");
wp.Credentials = nc;

HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(LookupURL + txtIPAddress.Text);
hwr.Proxy = wp;

hwr.Credentials = nc;

try
{
HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();

StreamReader sr = new StreamReader(response.GetResponseStream());

string respData = sr.ReadToEnd();

int startPos = respData.IndexOf("netname:");
int endPos = respData.IndexOf("country:");

string filteredData = respData.Substring(startPos, endPos - startPos);

string[] inforeceived = filteredData.Split('\n');

string netname = inforeceived[0];

string desc = inforeceived[1];

startPos = respData.IndexOf("[");
endPos = respData.IndexOf("]");

string location = respData.Substring(startPos, endPos - startPos).Replace("[","").Replace("]","");

lblLocation.Text = location;
lblNetworkName.Text = netname;
lblDesc.Text = desc;

}
catch(WebException we)
{
MessageBox.Show(we.Message);
}

this.btnLookup.Enabled = true;
}