Retrieving WhoIs information via .Net

Retrieving WhoIs information for domains via code is a relatively straight forward process with only one catch, you have to find the right WhoIs server to query.

Luckily I have found a great WhoIs Server List produced by Nir Sofer which lists the top level domains and their server.  The list is available for download here.

The code for retrieving the WhoIs query result is below:

string whoisServer = "";
string ret = "";
Socket s = null;

s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.Connect(new IPEndPoint(Dns.Resolve(whoisServer).AddressList[0], 43));

s.Send(Encoding.ASCII.GetBytes(domain + "\r\n"));
byte[] buffer = new byte[1024];
int recv = s.Receive(buffer);
  while (recv > 0)
  {
    ret += Encoding.ASCII.GetString(buffer, 0, recv);
    recv = s.Receive(buffer);
  }
s.Shutdown(SocketShutdown.Both);

s.Close();
return ret;