private static async Task OnQueryReceived(object sender, QueryReceivedEventArgs e) { var message = e.Query as DnsMessage; var response = message?.CreateResponseInstance(); if (message?.Questions.Count == 1) { // send query to upstream _servers var question = message.Questions[0]; DnsClient client = DnsClient.Default; if (FORCE_IPV4) { Random rand = new Random(); var ipv4DnsServers = DnsClient.GetLocalConfiguredDnsServers().Where(a => a.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); var list = ipv4DnsServers.OrderBy(a => rand.Next()).ToList(); client = new DnsClient(list, DnsClient.Default.QueryTimeout); } var upstreamResponse = await client.ResolveAsync(question.Name, question.RecordType, question.RecordClass); // if got an answer, copy it to the message sent to the client if (upstreamResponse != null) { foreach (var record in (upstreamResponse.AnswerRecords)) { response.AnswerRecords.Add(record); } foreach (var record in (upstreamResponse.AdditionalRecords)) { response.AdditionalRecords.Add(record); } response.ReturnCode = ReturnCode.NoError; // set the response e.Response = response; } } }
public static void Verify(MailAddress email) { // Try get SMTP server var client = new DnsClient(DnsClient.GetLocalConfiguredDnsServers(), 1000); var dnsMessage = client.Resolve(DomainName.Parse(email.Host), RecordType.Mx); if (dnsMessage == null) { throw new TimeOutException("Operation has timed out!"); } if (dnsMessage.ReturnCode == ReturnCode.NxDomain) { throw new NxDomainException("Domain not exists!"); } if (dnsMessage.ReturnCode != ReturnCode.NoError) { throw new DomainValidationException("Unable to validate domain!"); } if (!dnsMessage.AnswerRecords.Any()) { throw new NoMxRecordException("No MX records!"); } var mainServer = dnsMessage.AnswerRecords.OfType <MxRecord>().OrderBy(s => s.Preference).First(); // Try validate account var smtpClient = new SimpleSmtpClient(mainServer.ExchangeDomainName.ToString(), _smtpPort); var response = smtpClient.Read(); if (IsError(response.StatusCode)) { throw new EmailValidationException($"Connection refused: {response.Description}"); } response = smtpClient.SendCommand($"HELO {_identity}"); if (IsError(response.StatusCode)) { throw new EmailValidationException($"Greeting failed: {response.Description}"); } response = smtpClient.SendCommand($"VRFY {email.Address}"); if (!IsError(response.StatusCode)) { return; } if (response.StatusCode == SmtpStatusCode.MailboxUnavailable) { throw new NxEmailException($"Email does not exists: {response.Description}"); } response = smtpClient.SendCommand($"MAIL FROM:<{_sender}>"); if (IsError(response.StatusCode)) { throw new EmailValidationException($"SMTP server is insane: {response.Description}"); } response = smtpClient.SendCommand($"RCPT TO:<{email.Address}>"); if (IsError(response.StatusCode)) { throw new NxEmailException($"Email is invalid: {response.Description}"); } }