public void ResolveVerifyTTLUpdate() { using (DnsClient client = s_authoritativeResolverServer.CreateClient()) { DnsResponse response = client.Resolve(new DnsRequest(new DnsQuestion("direct.hisp.com", DnsStandard.RecordType.ANAME))); Thread.Sleep(2500); DnsResponse response2 = client.Resolve(new DnsRequest(new DnsQuestion("direct.hisp.com", DnsStandard.RecordType.ANAME))); for (int i = 0; i < response.AnswerRecords.Count; i++) { Assert.True(response.AnswerRecords[i].TTL > response2.AnswerRecords[i].TTL); } for (int i = 0; i < response.AdditionalRecords.Count; i++) { Assert.True(response.AdditionalRecords[i].TTL > response2.AdditionalRecords[i].TTL); } for (int i = 0; i < response.NameServerRecords.Count; i++) { Assert.True(response.NameServerRecords[i].TTL > response2.NameServerRecords[i].TTL); } } }
public static IEnumerable <string> GetMXRecords(string domain, out bool found) { var result = _dnsClient.Resolve(DomainName.Parse(domain), RecordType.Mx); if (result?.AnswerRecords == null) { found = false; return(BlankResult); } var records = result.AnswerRecords.OfType <MxRecord>(); found = records.Any(); return(records.Select(r => r.ExchangeDomainName.ToString())); }
public void CreateAResponseDumps(string domain) { DnsBuffer buff = new DnsBuffer(DnsStandard.MaxUdpMessageLength * 2); m_client.Resolve(DnsRequest.CreateA(domain)).Serialize(buff); byte[] bytes = buff.CreateReader().ReadBytes(); string path = Path.Combine(DnsResponsePath, string.Format("aname.{0}.bin", domain)).Replace("www.", ""); Console.WriteLine("Creating {0}", path); using (FileStream s = new FileStream(path, FileMode.OpenOrCreate)){ s.Write(bytes , 0 , bytes.Length); s.Close(); } }
public DnsResponse Get(DnsRequest request) { ushort requestID = request.RequestID; DnsResponse response = null; try { using (DnsClient client = new DnsClient(m_serverIP)) { if (m_timeout != null) { client.Timeout = m_timeout.Value; } response = client.Resolve(request); } } finally { if (response != null) { response.RequestID = requestID; } request.RequestID = requestID; } return(response); }
public void Dig() { try { //初始化DnsClient,第一个参数为DNS服务器的IP,第二个参数为超时时间 DnsClient dnsClient = new DnsClient(IPAddress.Parse(DnsServer), TimeOut); //解析域名。将域名请求发送至DNS服务器解析,参数为需要解析的域名 DnsMessage dnsMessage = dnsClient.Resolve(DomainName.Parse(Domain)); //TimeSpan = s.Elapsed; //若返回结果为空,或者存在错误,则该请求失败。 if (dnsMessage == null || (dnsMessage.ReturnCode != ReturnCode.NoError && dnsMessage.ReturnCode != ReturnCode.NxDomain)) { IsSuccess = false; return; } //循环遍历返回结果,将返回的IPV4记录添加到结果集List中。 if (dnsMessage != null) { foreach (DnsRecordBase dnsRecord in dnsMessage.AnswerRecords) { ARecord AR = dnsRecord as ARecord; if (AR != null) { IsSuccess = true; Record.Add(AR.Address.ToString()); } } } } catch (Exception) { } }
public static String ClientQuery(string domain) { List <IPAddress> dnss = new List <IPAddress> { }; dnss.AddRange(Dns.GetHostAddresses(dns)); var dnsClient = new DnsClient(dnss, 60); DnsMessage dnsMessage = dnsClient.Resolve(domain, RecordType.Txt); if ((dnsMessage == null) || ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain))) { Console.WriteLine("DNS request failed"); return(null); } else { foreach (DnsRecordBase dnsRecord in dnsMessage.AnswerRecords) { TxtRecord txtRecord = dnsRecord as TxtRecord; if (txtRecord != null) { return(txtRecord.TextData.ToString()); } } return(null); } }
private void Resolve(DnsRequest request) { DnsResponse matches = m_client.Resolve(request); Assert.NotNull(matches); Assert.True(matches.HasAnswerRecords, string.Format("{0}:{1}", request.Question.Type, request.Question.Domain)); }
public void ThreadProc(object state) { IEnumerable <string> domains = (IEnumerable <string>)state; using (DnsClient client = m_server.CreateClient()) { client.UseUDPFirst = m_udp; client.Timeout = m_timeout; foreach (string domain in domains) { try { DnsResponse response = client.Resolve(new DnsRequest(m_type, domain)); if (response.IsSuccess && response.HasAnswerRecords) { m_success++; } else { m_failure++; } } catch { m_failure++; } } } }
public void DnsResolve(string[] args) { string domain = args.GetRequiredValue(0); DnsStandard.RecordType recordType = args.GetOptionalEnum <DnsStandard.RecordType>(1, DnsStandard.RecordType.ANAME); try { using (DnsClient client = CreateClient()) { client.UseUDPFirst = (recordType != DnsStandard.RecordType.CERT); DnsResponse response = client.Resolve(new DnsRequest(recordType, domain)); if (response == null) { Console.WriteLine("No matches"); return; } m_recordPrinter.Print(response); } } catch (DnsServerException ex) { Console.WriteLine(ex.ResponseCode); } }
public void TestNotSupported(string domain, DnsStandard.RecordType type, bool useUDP) { DnsClient client = TestServer.Default.CreateClient(); client.UseUDPFirst = !useUDP; DnsResponse response = client.Resolve(new DnsRequest(type, domain)); Assert.True(!response.IsSuccess); }
static DnsMessageBase ProcessQuery(DnsMessageBase message, IPAddress clientAddress, ProtocolType protocol) { message.IsQuery = false; DnsMessage query = message as DnsMessage; if ((query != null) && (query.Questions.Count == 1)) { // send query to upstream server DnsQuestion question = query.Questions[0]; Random rnd = new Random(); Console.WriteLine(question.Name); System.Threading.Tasks.Parallel.ForEach(dnslist, (site, state) => { Console.WriteLine("Get Info from: " + site); DnsClient cd = new DnsClient(IPAddress.Parse(dnslist[rnd.Next(0, dnslist.Length - 1)]), 500); DnsMessage answer = cd.Resolve(question.Name, question.RecordType, question.RecordClass); if (answer != null) { foreach (DnsRecordBase record in (answer.AnswerRecords)) { lock (query) { query.AnswerRecords.Add(record); } Console.WriteLine(record.Name); } foreach (DnsRecordBase record in (answer.AdditionalRecords)) { lock (query) { query.AnswerRecords.Add(record); } Console.WriteLine(record.Name); } lock (query) { query.ReturnCode = ReturnCode.NoError; state.Break(); } } }); // if got an answer, copy it to the message sent to the client } if (query.ReturnCode == ReturnCode.NoError) { return(query); } // Not a valid query or upstream server did not answer correct message.ReturnCode = ReturnCode.ServerFailure; return(message); }
static void Main(string[] args) { var records = DnsClient.Resolve <SrvRecord>("_e2tp._tcp.sycadetest.com"); //records.OrderByPriorityAndWeight(); foreach (var record in records) { Console.WriteLine(record); } }
public async Task RecursiveResolverTest() { var resolver = new RecursiveRequestResolver(new ParallelRequestResolver( UdpRequestResolver.Create(IPAddress.Parse("192.33.4.12")), UdpRequestResolver.Create(IPAddress.Parse("192.41.162.30")))); DnsClient client = new DnsClient(resolver); var response = await client.Resolve("google.com", RecordType.A); Assert.Equal(ResponseCode.NoError, response.ResponseCode); Assert.True(response.AnswerRecords.Count > 0); }
static DnsMessageBase ProcessQuery(DnsMessageBase message, IPAddress clientAddress, ProtocolType protocol) { message.IsQuery = false; DnsMessage query = message as DnsMessage; if ((query != null) && (query.Questions.Count == 1)) { // send query to upstream server DnsQuestion question = query.Questions[0]; DnsMessage answer = null; if (question.RecordType == RecordType.A) // IPv4, so try IPv6 first then IPv4 { DnsClient dc = new DnsClient(IPAddress.Parse("2001:470:20::2"), 1000); answer = dc.Resolve(question.Name, RecordType.A6, question.RecordClass); // if got an answer, copy it to the message sent to the client if (answer != null) { foreach (DnsRecordBase record in (answer.AnswerRecords)) { query.AnswerRecords.Add(record); } foreach (DnsRecordBase record in (answer.AdditionalRecords)) { query.AnswerRecords.Add(record); } query.ReturnCode = ReturnCode.NoError; return(query); } } answer = DnsClient.Default.Resolve(question.Name, question.RecordType, question.RecordClass); if (answer != null) { foreach (DnsRecordBase record in (answer.AnswerRecords)) { query.AnswerRecords.Add(record); } foreach (DnsRecordBase record in (answer.AdditionalRecords)) { query.AnswerRecords.Add(record); } query.ReturnCode = ReturnCode.NoError; return(query); } } // Not a valid query or upstream server did not answer correct message.ReturnCode = ReturnCode.ServerFailure; return(message); }
/// <summary> /// Resolves a specified host to IP address. /// </summary> /// <param name="dnsHostName">DNS host name to resolve.</param> /// <returns>Resolved host name if host is found, or null if lookup fails.</returns> public IPAddress Resolve(string dnsHostName) { var dnsResponse = _client.Resolve(dnsHostName); if (dnsResponse == null || (dnsResponse.ReturnCode != ReturnCode.NoError)) { return(null); } var record = dnsResponse.AnswerRecords.First() as ARecord; return((record != null) ? record.Address : null); }
/// <summary> /// Queries the DNS server for the specified record type. /// </summary> /// <param name="query">The query.</param> /// <param name="recordType">Type of the record.</param> /// <param name="dnsServer">The DNS server.</param> /// <param name="port">The port.</param> /// <returns>Queries the DNS server for the specified record type of the result produced by this Task.</returns> public static async Task <DnsQueryResult> QueryDnsAsync(string query, DnsRecordType recordType, IPAddress dnsServer, int port) { if (query == null) { throw new ArgumentNullException(nameof(query)); } var client = new DnsClient(dnsServer, port); var response = await client.Resolve(query, recordType).ConfigureAwait(false); return(new DnsQueryResult(response)); }
public void ResolveWithNameErrors(string domain, DnsStandard.RecordType type) { using (DnsClient client = s_authoritativeResolverServer.CreateClient()) { DnsResponse response = client.Resolve(new DnsRequest(new DnsQuestion(domain, type))); Assert.False(response.HasAdditionalRecords); Assert.False(response.HasAnswerRecords); Assert.False(response.HasAnyRecords); Assert.True(response.IsNameError); } }
static IEnumerable <SRVRecord> RequestSrv(DnsClient client, string domain) { var dnsRequest = new DnsRequest(DnsStandard.RecordType.SRV, domain); var response = client.Resolve(dnsRequest); if (response == null || !response.HasAnswerRecords) { return(null); } return(response.AnswerRecords.SRV .OrderBy(r => r.Priority) .ThenByDescending(r => r.Weight)); }
private DnsMessage ResolveDnsQuery([NotNull] DnsQuestion question) { var ips = new[] { _endDnsIP }; var client = new DnsClient(ips, (int)NormalDnsQueryTimeout.TotalMilliseconds); var answer = client.Resolve(question.Name, question.RecordType, question.RecordClass); if (answer == null) { // Failed... } return(answer); }
private DnsMessageBase ProcessQuery(DnsMessageBase message, IPAddress clientAddress, ProtocolType protocol) { message.IsQuery = false; DnsMessage query = message as DnsMessage; if ((query != null) && (query.Questions.Count == 1)) { // send query to upstream server DnsQuestion question = query.Questions[0]; DnsMessage answer; List <ARecord> predefinedRecords = ReadItems(); List <string> clients = ReadClients(); if (predefinedRecords != null && predefinedRecords.Select(r => r.Name).Contains(question.Name) && clients != null && clients.Contains(clientAddress.ToString())) { answer = new DnsMessage(); answer.AnswerRecords.Add(predefinedRecords.First(r => r.Name == question.Name)); } else { List <IPAddress> dnsServers = new List <IPAddress> { IPAddress.Parse("8.8.8.8"), IPAddress.Parse("8.8.4.4") }; DnsClient client = new DnsClient(dnsServers, 30); answer = client.Resolve(question.Name, question.RecordType, question.RecordClass); } // if got an answer, copy it to the message sent to the client if (answer != null) { foreach (DnsRecordBase record in (answer.AnswerRecords)) { query.AnswerRecords.Add(record); } foreach (DnsRecordBase record in (answer.AdditionalRecords)) { query.AnswerRecords.Add(record); } query.ReturnCode = ReturnCode.NoError; return(query); } } // Not a valid query or upstream server did not answer correct message.ReturnCode = ReturnCode.ServerFailure; return(message); }
private static void Lookup(string domaim, DnsClient dns, ISet <string> caches, ISet <string> ranges) { foreach (var resp in dns.Resolve(domaim, RecordType.Txt).AnswerRecords.Select(resp => resp.ToString())) { foreach (Match m in RxSpfIpv4.Matches(resp)) { ranges.Add(m.Groups[1].Value); } foreach ( var dom in RxSpfInclude.Matches(resp).Cast <Match>().Select(m => m.Groups[1].Value).Where(caches.Add)) { Lookup(dom, dns, caches, ranges); } } }
private DnsMessage ResolveDnsQuery(DnsQuestion question) { var ips = new List <IPAddress>() { IPAddress.Parse(_endDnsIp) }; var client = new DnsClient(ips, 8000); DnsMessage answer = client.Resolve(question.Name, question.RecordType, question.RecordClass); if (answer == null) { LogMessage(null, string.Format("Failed to resolve DNS Name for {0}", question.Name)); } return(answer); }
private TextResourceRecord SearchTxt(string query) { try { var txt = _dnsClient.Resolve(query, RecordType.TXT).Result; var rblMessage = txt.AnswerRecords .Where(a => a.Type.Equals(RecordType.TXT)) .Cast <TextResourceRecord>() .FirstOrDefault(); return(rblMessage); } catch { return(null); } }
public StubZone(DnsServer dnsServer, string name, string primaryNameServerAddresses = null) : base(name) { _dnsServer = dnsServer; DnsQuestionRecord soaQuestion = new DnsQuestionRecord(name, DnsResourceRecordType.SOA, DnsClass.IN); DnsDatagram soaResponse = null; if (primaryNameServerAddresses == null) { soaResponse = _dnsServer.DirectQuery(soaQuestion); } else { DnsClient dnsClient = new DnsClient(primaryNameServerAddresses); dnsClient.Proxy = _dnsServer.Proxy; dnsClient.PreferIPv6 = _dnsServer.PreferIPv6; dnsClient.Retries = _dnsServer.Retries; dnsClient.Timeout = _dnsServer.Timeout; soaResponse = dnsClient.Resolve(soaQuestion); } if ((soaResponse == null) || (soaResponse.Answer.Count == 0) || (soaResponse.Answer[0].Type != DnsResourceRecordType.SOA)) { throw new DnsServerException("DNS Server failed to find SOA record for: " + name); } DnsSOARecord receivedSoa = soaResponse.Answer[0].RDATA as DnsSOARecord; DnsSOARecord soa = new DnsSOARecord(receivedSoa.PrimaryNameServer, receivedSoa.ResponsiblePerson, receivedSoa.Serial - 1, receivedSoa.Refresh, receivedSoa.Retry, receivedSoa.Expire, receivedSoa.Minimum); DnsResourceRecord[] soaRR = new DnsResourceRecord[] { new DnsResourceRecord(_name, DnsResourceRecordType.SOA, DnsClass.IN, soa.Refresh, soa) }; if (!string.IsNullOrEmpty(primaryNameServerAddresses)) { soaRR[0].SetGlueRecords(primaryNameServerAddresses); } _entries[DnsResourceRecordType.SOA] = soaRR; _isExpired = true; //new stub zone is considered expired till it refreshes _refreshTimer = new Timer(RefreshTimerCallback, null, Timeout.Infinite, Timeout.Infinite); }
public static List <IPAddress> Get_IP_Address_List(string domain) { DnsMessage answer = DnsClient.Resolve(DomainName.Parse(domain)); List <IPAddress> ipAddresses = new List <IPAddress>(); if (answer != null) { foreach (DnsRecordBase dnsRecord in answer.AnswerRecords) { if (dnsRecord is ARecord aRecord) { ipAddresses.Add(aRecord.Address); } } } return(ipAddresses); }
static void Main(string[] args) { // test dnsServer. using (DnsServer server = new DnsServer(System.Net.IPAddress.Loopback, 10, 10)) { server.QueryReceived += Server_QueryReceived; server.Start(); // test DnsClient dc = new DnsClient(IPAddress.Parse("127.0.0.1"), 5000); //DnsMessage msg = dc.Resolve(DomainName.Parse("www.google.com"), RecordType.A); DnsMessage msg = dc.Resolve(DomainName.Parse("www.google.com")); Console.WriteLine("Press any key to stop server"); Console.ReadLine(); server.Stop(); } }
private DnsMessage GetDnsMessage(string domainName, RecordType?type = null) { if (string.IsNullOrEmpty(domainName)) { throw new ArgumentNullException("domainName"); } var domain = DomainName.Parse(domainName); var dnsMessage = type.HasValue ? _dnsClient.Resolve(domain, type.Value) : _dnsClient.Resolve(domain); if ((dnsMessage == null) || ((dnsMessage.ReturnCode != ReturnCode.NoError) && (dnsMessage.ReturnCode != ReturnCode.NxDomain))) { throw new SystemException(); // DNS request failed } return(dnsMessage); }
int getping(string ip) { List <long> rt = new List <long>(); var timeout = 1000; var buffer = new byte[] { 0, 0, 0, 0 }; // создаем и отправляем ICMP request var ping = new Ping(); for (int i = 0; i < 1; i++) { var reply = ping.Send(ip, timeout, buffer, new PingOptions { Ttl = 128 }); if (reply.Status == IPStatus.Success) { rt.Add(reply.RoundtripTime); } else { DateTime dt1 = DateTime.Now; DnsClient cd = new DnsClient(IPAddress.Parse(ip), timeout); DnsMessage answer = cd.Resolve(qsample.Name, qsample.RecordType, qsample.RecordClass); DateTime dt2 = DateTime.Now; TimeSpan ts = dt2 - dt1; rt.Add((long)ts.TotalMilliseconds); } Application.DoEvents(); Thread.Sleep(5); } if (rt.Count > 0) { double iq = rt.Average(); iq = Math.Ceiling(iq); return((int)iq); } else { return(1000); } // если ответ успешен }
/// <summary> /// DNS解析 /// </summary> /// <param name="dnsServer">DNS服务器IP</param> /// <param name="timeOut">解析超时时间</param> /// <param name="url">解析网址</param> /// <param name="isSuccess">是否解析成功</param> /// <returns>解析到的IP信息</returns> public static IPAddress DnsResolver(string dnsServer, int timeOut, string url, out bool isSuccess) { if (string.IsNullOrEmpty(dnsServer)) { throw new ArgumentNullException(dnsServer); } if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException(url); } //初始化DnsClient,第一个参数为DNS服务器的IP,第二个参数为超时时间 var dnsClient = new DnsClient(IPAddress.Parse(dnsServer), timeOut); //解析域名。将域名请求发送至DNS服务器解析,第一个参数为需要解析的域名,第二个参数为 //解析类型, RecordType.A为IPV4类型 //DnsMessage dnsMessage = dnsClient.Resolve("www.sina.com", RecordType.A); var s = new Stopwatch(); s.Start(); var dnsMessage = dnsClient.Resolve(DomainName.Parse(url)); s.Stop(); //若返回结果为空,或者存在错误,则该请求失败。 if (dnsMessage == null || (dnsMessage.ReturnCode != ReturnCode.NoError && dnsMessage.ReturnCode != ReturnCode.NxDomain)) { isSuccess = false; } //循环遍历返回结果,将返回的IPV4记录添加到结果集List中。 if (dnsMessage != null) { foreach (var dnsRecord in dnsMessage.AnswerRecords) { var aRecord = dnsRecord as ARecord; if (aRecord == null) { continue; } isSuccess = true; return(aRecord.Address); } } isSuccess = false; return(null); }
private DnsMessageBase ProcessQuery(DnsMessageBase message, IPAddress clientAddress, ProtocolType protocol) { message.IsQuery = false; DnsMessage query = message as DnsMessage; if ((query != null) && (query.Questions.Count == 1)) { DnsQuestion question = query.Questions[0]; if (question.Name.Equals(domainToSpoof, StringComparison.InvariantCultureIgnoreCase)) { query.AnswerRecords.Add(new ARecord(domainToSpoof, 3600, spoofedIp)); query.ReturnCode = ReturnCode.NoError; return(query); } else { // send query to upstream server DnsMessage answer = client.Resolve(question.Name, question.RecordType, question.RecordClass); // if got an answer, copy it to the message sent to the client if (answer != null) { foreach (DnsRecordBase record in (answer.AnswerRecords)) { query.AnswerRecords.Add(record); } foreach (DnsRecordBase record in (answer.AdditionalRecords)) { query.AnswerRecords.Add(record); } query.ReturnCode = ReturnCode.NoError; return(query); } } } // Not a valid query or upstream server did not answer correct message.ReturnCode = ReturnCode.ServerFailure; return(message); }