public static void Main(string[] args) { DnsServer server = null; (new Thread(() => { server = new DnsServer("8.8.8.8"); server.Responded += (request, response) => Console.WriteLine("{0} => {1}", request, response); server.MasterFile.AddIPAddressResourceRecord("google.com", "127.0.0.1"); server.Listen(); })).Start(); Thread.Sleep(1000); //Client client = new Client("72.21.204.209"); //Client client = new Client("8.8.8.8"); DnsClient client = new DnsClient("127.0.0.1"); client.Reverse(IPAddress.Parse("173.194.69.100")); client.Lookup("google.com"); //client.Lookup("dr.dk"); //Console.WriteLine(client.Resolve("dnstest.managemydedi.com", RecordType.AAAA)); client.Lookup("cnn.com"); server.Close(); }
public static byte[] ByteRequest(string url) { Log.O("Downloading: " + url); var wc = new WebClient(); if (_proxy != null) { wc.Proxy = _proxy; } var uri = new Uri(url); if (!string.IsNullOrEmpty(_dns)) { var host = uri.Host; if (!_dnsCache.ContainsKey(host)) { var dns = new DnsClient(_dns); var resolved = dns.Lookup(host); resolved.Wait(); _dnsCache[host] = resolved.Result.FirstOrDefault().ToString(); } uri = uri.ReplaceHost(_dnsCache[host]); wc.Headers.Add("Host", host); } return(wc.DownloadData(uri)); }
public async Task ClientNameError() { DnsClient client = new DnsClient(new NameErrorRequestResolver()); await Assert.ThrowsAsync<ResponseException>(() => { return client.Lookup("google.com"); }); }
private async Task <ResolvedDomain> Resolve(string domain) { var servers = await System.Net.Dns.GetHostAddressesAsync(_dnsServer); var dnsServerIp = servers.First(); var mdl = new ResolvedDomain() { Name = domain, IsResolved = false }; try { var client = new DnsClient(dnsServerIp); var resp = await client.Lookup(_idnMapping.GetAscii(domain)); mdl.IsResolved = true; mdl.IPAddresses = resp.Select(x => x.ToString()).ToHashSet(); return(mdl); } catch (Exception) { //Logger.Log($"[Resolve] fail {domain}", ex, LogType.INFO); return(mdl); } }
/// <summary> /// Gets the DNS records of a domain. /// /// </summary> /// <param name="domain">Domain to query for DNS records</param> /// <param name="localDNSIPs">List of local DNS Resolver IPs to do the lookup</param> /// <returns></returns> public async Task <CollatedRecords> GetRecordsOfDomain(Uri domain, List <IPAddress> localDNSIPs) { IList <IPAddress> respIPs = new List <IPAddress>(); IResponse resp = null; foreach (var dnsIP in localDNSIPs) { DnsClient cli = new DnsClient(dnsIP); ClientRequest req = cli.Create(); req.RecursionDesired = true; req.Questions.Add(new Question(Domain.FromString(domain.Host), RecordType.ANY)); try { resp = await req.Resolve(); respIPs = await cli.Lookup(domain.Host); } catch { Console.Error.WriteLine("Swallowed lookup exception."); } if (resp != null && resp.ResponseCode.Equals(ResponseCode.NoError)) { break; } } if (resp == null) { throw new InvalidOperationException("Unable to get a valid response from the domain, check input."); } return(new CollatedRecords(resp, respIPs)); }
/// <summary> /// Gets the DNS host entry (a list of IP addresses) for the domain name. /// </summary> /// <param name="fqdn">The FQDN.</param> /// <param name="dnsServer">The DNS server.</param> /// <param name="port">The port.</param> /// <returns> /// An array of local ip addresses of the result produced by this task. /// </returns> /// <exception cref="ArgumentNullException">fqdn.</exception> public static async Task <IPAddress[]> GetDnsHostEntryAsync(string fqdn, IPAddress dnsServer, int port) { if (fqdn == null) { throw new ArgumentNullException(nameof(fqdn)); } if (fqdn.IndexOf(".", StringComparison.Ordinal) == -1) { fqdn += "." + IPGlobalProperties.GetIPGlobalProperties().DomainName; } while (true) { if (!fqdn.EndsWith(".", StringComparison.OrdinalIgnoreCase)) { break; } fqdn = fqdn.Substring(0, fqdn.Length - 1); } var client = new DnsClient(dnsServer, port); var result = await client.Lookup(fqdn).ConfigureAwait(false); return(result.ToArray()); }
public async Task ClientLookup() { DnsClient client = new DnsClient(new IPAddressRequestResolver()); IList<IPAddress> ips = await client.Lookup("google.com"); Assert.Equal(1, ips.Count); Assert.Equal("192.168.0.1", ips[0].ToString()); }
public async Task ParallelLookupTest() { DnsClient client = new DnsClient(new ParallelRequestResolver(new NameErrorRequestResolver(), new IPAddressRequestResolver())); IList <IPAddress> ips = await client.Lookup("google.com"); Assert.Equal(1, ips.Count); Assert.Equal("192.168.0.1", ips[0].ToString()); }
public IPAddress TryResolve(string hostname) { // Bind to a Domain Name Server var client = new DnsClient("8.8.8.8"); // Returns a list of IPs var ips = client.Lookup(hostname).Result; return(ips.Count > 0 ? ips[0] : null); }
public static void Main(string[] args) { DnsClient client = new DnsClient("8.8.8.8"); foreach (string domain in args) { IList <IPAddress> ips = client.Lookup(domain); Console.WriteLine("{0} => {1}", domain, string.Join(", ", ips)); } }
public async static Task MainAsync(string[] args) { DnsClient client = new DnsClient("8.8.8.8"); foreach (string domain in args) { IList <IPAddress> ips = await client.Lookup(domain).ConfigureAwait(false); Console.WriteLine("{0} => {1}", domain, string.Join(", ", ips)); } }
public async static Task LookupAsync(params string[] args) { DnsClient client = new DnsClient("127.0.0.1", 53); foreach (string domain in args) { IList <IPAddress> ips = await client.Lookup(domain); Console.WriteLine("[DNSClient] {0} => {1}", domain, string.Join(", ", ips)); } }
public async static Task MainAsync() { MasterFile masterFile = new MasterFile(); DnsServer server = new DnsServer(masterFile, "8.8.8.8"); masterFile.AddIPAddressResourceRecord("google.com", "127.0.0.1"); server.Requested += (request) => Console.WriteLine("Requested: {0}", request); server.Responded += (request, response) => Console.WriteLine("Responded: {0} => {1}", request, response); server.Errored += (e) => Console.WriteLine("Errored: {0}", e.Message); server.Listening += () => Console.WriteLine("Listening"); server.Listening += async() => { DnsClient client = new DnsClient("127.0.0.1", PORT); await client.Lookup("google.com"); await client.Lookup("cnn.com"); server.Dispose(); }; await server.Listen(PORT); }
public static void Main(string[] args) { DnsServer server = null; (new Thread(() => { server = new DnsServer("8.8.8.8"); server.Requested += (request) => Console.WriteLine("Requested: {0}", request); server.Responded += (request, response) => Console.WriteLine("Responded: {0} => {1}", request, response); server.MasterFile.AddIPAddressResourceRecord("google.com", "127.0.0.1"); server.Listen(); })).Start(); Thread.Sleep(1000); DnsClient client = new DnsClient("127.0.0.1"); client.Lookup("google.com"); client.Lookup("cnn.com"); server.Close(); }
public async static Task MainAsync() { DnsServer server = new DnsServer("8.8.8.8"); server.Requested += (request) => Console.WriteLine("Requested: {0}", request); server.Responded += (request, response) => Console.WriteLine("Responded: {0} => {1}", request, response); server.Errored += (e) => Console.WriteLine("Errored: {0}", e.Message); server.MasterFile.AddIPAddressResourceRecord("google.com", "127.0.0.1"); #pragma warning disable 4014 server.Listen(PORT); #pragma warning restore 4014 await Task.Delay(1000); DnsClient client = new DnsClient("127.0.0.1", PORT); await client.Lookup("google.com"); await client.Lookup("cnn.com"); server.Dispose(); }
public static string StringRequest(string url, string data) { var wc = new WebClient(); if (_proxy != null) { wc.Proxy = _proxy; } wc.Encoding = System.Text.Encoding.UTF8; wc.Headers.Add("Content-Type", "text/plain; charset=utf8"); wc.Headers.Add("User-Agent", _userAgent); var uri = new Uri(url); if (!string.IsNullOrEmpty(_dns)) { var host = uri.Host; if (!_dnsCache.ContainsKey(host)) { var dns = new DnsClient(_dns); var resolved = dns.Lookup(host); resolved.Wait(); _dnsCache[host] = resolved.Result.FirstOrDefault().ToString(); } uri = uri.ReplaceHost(_dnsCache[host]); wc.Headers.Add("Host", host); } string response = string.Empty; try { response = wc.UploadString(uri, "POST", data); } catch (WebException wex) { Log.O("StringRequest Error: " + wex.ToString()); //Wait and Try again, just in case Thread.Sleep(500); response = wc.UploadString(uri, "POST", data); } return(response); }
private ResponseItem Search(string query, RecordType recordType) { _logger.LogInformation($"Checking blacklisting for {query}"); var result = _cache.FirstOrDefault(c => c.Query.Equals(query)); if (result != null) { _logger.LogInformation("Cached item found"); return(result); } if (recordType != RecordType.A && recordType != RecordType.AAAA) { return(null); } foreach (var rbl in _rblList) { _logger.LogInformation($"Checking {rbl}"); try { var resolves = _dnsClient.Lookup($"{query}.{rbl}", recordType).Result; if (!resolves.Any()) { continue; } var rblMessage = SearchTxt($"{query}.{rbl}"); _logger.LogInformation("Found a match"); result = new ResponseItem(query, rbl, rblMessage?.ToStringTextData(), resolves.First()); _cache.Add(result); return(result); } catch (Exception e) { // ignored } } _logger.LogInformation("No matches found"); return(null); }
public async Task ParallelLookupError() { DnsClient client = new DnsClient(new ParallelRequestResolver(new NameErrorRequestResolver(), new NameErrorRequestResolver(), new ThrowsExceptionRequestResolver(), new ThrowsExceptionRequestResolver())); var responseException = await Assert.ThrowsAsync <ResponseException>(() => { return(client.Lookup("google.com")); }); client = new DnsClient(new ParallelRequestResolver(new ThrowsExceptionRequestResolver(), new ThrowsExceptionRequestResolver())); var aggregateException = await Assert.ThrowsAsync <AggregateException>(() => { return(client.Lookup("google.com")); }); Assert.Equal(2, aggregateException.InnerExceptions.Count); Assert.All(aggregateException.InnerExceptions, i => Assert.IsType <NotImplementedException>(i)); }
public async Task <IPAddress> TryResolve(string hostname) { IList <IPAddress> ips = null; if (IPAddress.TryParse(hostname, out var address)) { return(address); } try { ips = await _client.Lookup(hostname); } catch { // ignore } return(ips?.Count > 0 ? ips[0] : null); }
static async void Run() { try { // Bind to a Domain Name Server DnsClient client = new DnsClient("8.8.8.8"); // Create request bound to 8.8.8.8 ClientRequest request = client.Create(); // Returns a list of IPs IList <IPAddress> ips = await client.Lookup("framesoft.ir"); // Get the domain name belonging to the IP (google.com) //string domain = await client.Reverse("173.194.69.100"); } catch (Exception ex) { } }
/// <summary> /// Gets the DNS host entry (a list of IP addresses) for the domain name. /// </summary> /// <param name="fqdn">The FQDN.</param> /// <param name="dnsServer">The DNS server.</param> /// <param name="port">The port.</param> /// <returns>An array of local ip addresses</returns> public static IPAddress[] GetDnsHostEntry(string fqdn, IPAddress dnsServer, int port) { if (fqdn.IndexOf(".", StringComparison.Ordinal) == -1) { fqdn += "." + IPGlobalProperties.GetIPGlobalProperties().DomainName; } while (true) { if (fqdn.EndsWith(".") == false) { break; } fqdn = fqdn.Substring(0, fqdn.Length - 1); } var client = new DnsClient(dnsServer, port); var result = client.Lookup(fqdn); return(result.ToArray()); }
public static bool IsDkimSettedUpCorrectForDomain(string domain_name, string selector, string dkim_record, ILogger logger = null) { try { var domain_txt_records = DnsClient.Lookup(selector + "._domainkey." + domain_name, DnsClient.RecordType.TXT); if (domain_txt_records == null) { throw new ArgumentException("DKIM record on your domain is missing."); } return(domain_txt_records.AnswerRecords.Any(re => re.Data.Trim('\"') == dkim_record)); } catch (Exception ex) { if (logger != null) { logger.Debug("DnsClient.Lookup: domain: '{0}' selector: '{1}._domainkey.' dkim_pk: '{2}'\r\nException: {3}", domain_name, selector, dkim_record, ex.ToString()); } return(false); } }
public static bool IsTxtRecordCorrect(string domain_name, string txt_record, ILogger logger = null) { try { var domain_txt_records = DnsClient.Lookup(domain_name, DnsClient.RecordType.TXT); if (domain_txt_records == null) { throw new ArgumentException("TXT record on your domain is missing."); } return(domain_txt_records.AnswerRecords.Any(re => re.Data.Trim('\"') == txt_record)); } catch (Exception ex) { if (logger != null) { logger.Debug("DnsClient.LookupMX: domain: '{0}' txt: '{1}'\r\nException: {2}", domain_name, txt_record, ex.ToString()); } return(false); } }
/// <summary> /// Detects whether our DNS servers are down. /// /// This one's a little sticky because we don't know whether internet is down for sure. /// I think it's easy enough to just assume that if we can't reach our DNS servers we should probably flip the switch. /// /// If first server checked is up, no more are checked, and so on. /// </summary> /// <returns>Returns true if at least one of the servers in the configuration returns a response or if there are none configured. Returns false if all servers tried do not return a response.</returns> public async Task <bool> IsDnsUp() { if (lastDnsCheck.AddMinutes(5) > DateTime.Now) { return(lastDnsResult); } lastDnsCheck = DateTime.Now; bool ret = false; if (m_provider.Config == null) { // We can't really make a decision on enforcement here, but just return true anyway. return(true); } string primaryDns = m_provider.Config.PrimaryDns; string secondaryDns = m_provider.Config.SecondaryDns; if (string.IsNullOrWhiteSpace(primaryDns) && string.IsNullOrWhiteSpace(secondaryDns)) { ret = true; } else { List <string> dnsSearch = new List <string>(); if (!string.IsNullOrWhiteSpace(primaryDns)) { dnsSearch.Add(primaryDns); } if (!string.IsNullOrWhiteSpace(secondaryDns)) { dnsSearch.Add(secondaryDns); } int failedDnsServers = 0; foreach (string dnsServer in dnsSearch) { try { DnsClient client = new DnsClient(dnsServer); IList <IPAddress> ips = await client.Lookup("testdns.cloudveil.org"); if (ips != null && ips.Count > 0) { ret = true; break; } else { failedDnsServers++; } } catch (Exception ex) { failedDnsServers++; m_logger.Error($"Failed to contact DNS server {dnsServer}"); LoggerUtil.RecursivelyLogException(m_logger, ex); } } } lastDnsResult = ret; return(ret); }