Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Net;
- using System.Net.Sockets;
- using System.Diagnostics;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- namespace NWhois
- {
- class WhoisClient
- {
- #region privatedata
- #endregion
- #region instance
- public WhoisClient()
- {
- }
- #endregion
- #region properties
- #endregion
- #region methods
- public string Whois(string query, string server = "", int port = 43)
- {
- string srv = server;
- if (string.IsNullOrEmpty(srv))
- {
- srv = getServer(query);
- if (string.IsNullOrEmpty(srv)) return null;
- }
- string result = QuerySrv(query, srv, port);
- string single = getSingle(result, query);
- if (!string.IsNullOrEmpty(single))
- {
- result = QuerySrv(single, srv, port);
- string patt = string.Format("domain name: {0}", query.ToLower());
- int pos = result.ToLower().IndexOf(patt);
- if (pos > 0) {
- result = result.Substring(pos);
- }
- }
- string hint = getHint(result, "whois server:");
- if (!string.IsNullOrEmpty(hint))
- {
- result = QuerySrv(query, hint, port);
- }
- return result;
- }
- #endregion
- #region privatecode
- private string getServer(string query)
- {
- string buff = QuerySrv(query, "whois.iana.org" , 43);
- if (string.IsNullOrEmpty(buff)) return null;
- string srv = getHint(buff, "whois:");
- return srv;
- }
- private string getHint(string data, string tag)
- {
- string buf = data.ToLower();
- int pos = buf.IndexOf(tag);
- if (pos < 1) return null;
- buf = buf.Substring(pos + tag.Length);
- pos = buf.IndexOf("\n");
- if (pos < 1) return null;
- buf = buf.Substring(0, pos).Trim();
- return buf;
- }
- private string getSingle(string data, string query)
- {
- string buf = data.ToLower();
- int pos = buf.IndexOf("to single out one record");
- if (pos < 1) return null;
- return "=" + query.ToUpper();
- }
- private string QuerySrv(string query, string server, int port = 43)
- {
- string result = null;
- // Console.WriteLine(string.Format("QuerySrv(\"{0}\",\"{1}\",{2})", query, server, port));
- try
- {
- Encoding enc = Encoding.ASCII;
- TcpClient sock = new TcpClient(server, port);
- using (Stream s = sock.GetStream())
- {
- byte[] qry = enc.GetBytes(query + "\r\n");
- byte[] buf = new byte[8192];
- StringBuilder resp = new StringBuilder();
- s.Write(qry, 0, qry.Length);
- int nbytes = 0;
- do
- {
- nbytes = s.Read(buf, 0, buf.Length);
- if (nbytes > 0)
- {
- resp.Append(enc.GetString(buf, 0, nbytes));
- }
- } while (nbytes > 0);
- result = resp.ToString();
- }
- sock.Close();
- }
- catch (Exception ex)
- {
- Console.WriteLine(string.Format("ERR: QuerySrv(\"{0}\",\"{1}\",{2}) :: {3}", query, server, port, ex.Message));
- result = null;
- }
- return result;
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement