Friday, May 14, 2010

Get WhoIs Information from a domain name in C#

I needed to get the WhoIs information for a domain using the simplest way possible.

I could have used a WebService such as WebServiceX.net's http://www.webservicex.net/whois.asmx

But I decided to just talk to the whois servers directly, all I needed to do was open a socket send a request and then read from the socket.

I used the list from http://www.nirsoft.net/whois_servers_list.html then wrote some code, here is an example of how I did it for anyone that needs the information.




using System;
using System.Net.Sockets;
using System.IO;


namespace WHOISConsole
{
class Program
{
static void Main(string[] args)
{

string whoisServer = "whois.nic.uk";

string domainName = "bbc.co.uk";

Console.WriteLine(GetWHOIS(whoisServer,domainName));

Console.ReadKey();
}

///
/// Get the WHO IS Info for a domain name
///

/// The server to use, changes per domain
/// Domain we are looking up
///
public static string GetWHOIS(string whoisServer, string domainName)
{
// Port 43 is standard
using (var tcpClient = new TcpClient(whoisServer, 43))
{
// get the underlying stream
using (var networkStream = tcpClient.GetStream())
{
// we need to write to the stream
using (var streamWriter = new StreamWriter(networkStream))
{
// write the domain and a new line, CRLF
streamWriter.WriteLine(domainName);

// flush it to actually send it
streamWriter.Flush();
}

using (var streamReader = new StreamReader(networkStream))
{
// now read from the stream
return streamReader.ReadToEnd();
}

}
}

}
}
}





Any comments please post below. Thanks.

0 comments:

Post a Comment