forked from BornToBeRoot/NETworkManager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWhois.cs
More file actions
80 lines (60 loc) · 2.47 KB
/
Whois.cs
File metadata and controls
80 lines (60 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace NETworkManager.Models.Network
{
public static class Whois
{
#region Variables
private static readonly string WhoisServerFilePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Resources", "WhoisServers.xml");
private static readonly List<WhoisServerInfo> WhoisServerList;
private static readonly Lookup<string, WhoisServerInfo> WhoisServers;
#endregion
#region Constructor
static Whois()
{
var document = new XmlDocument();
document.Load(WhoisServerFilePath);
WhoisServerList = new List<WhoisServerInfo>();
foreach (XmlNode node in document.SelectNodes("/WhoisServers/WhoisServer"))
{
if (node == null)
continue;
WhoisServerList.Add(new WhoisServerInfo(node.SelectSingleNode("Server")?.InnerText, node.SelectSingleNode("TLD")?.InnerText));
}
WhoisServers = (Lookup<string, WhoisServerInfo>)WhoisServerList.ToLookup(x => x.Tld);
}
#endregion
#region Methods
public static Task<string> QueryAsync(string domain, string whoisServer)
{
return Task.Run(() => Query(domain, whoisServer));
}
public static string Query(string domain, string whoisServer)
{
var tcpClient = new TcpClient(whoisServer, 43);
var networkStream = tcpClient.GetStream();
var bufferedStream = new BufferedStream(networkStream);
var streamWriter = new StreamWriter(bufferedStream);
streamWriter.WriteLine(domain);
streamWriter.Flush();
var streamReader = new StreamReader(bufferedStream);
var stringBuilder = new StringBuilder();
while (!streamReader.EndOfStream)
stringBuilder.AppendLine(streamReader.ReadLine());
return stringBuilder.ToString();
}
public static string GetWhoisServer(string domain)
{
var domainParts = domain.Split('.');
// TLD to upper because the lookup is case sensitive
return WhoisServers[domainParts[domainParts.Length - 1].ToUpper()].FirstOrDefault()?.Server;
}
#endregion
}
}