public async Task <IDnsResponse> Resolve(IDnsRequest request) { using (UdpClient udp = new UdpClient()) { await udp .SendAsync(request.ToArray(), request.Size, dns) .WithCancellationTimeout(timeout); UdpReceiveResult result = await udp.ReceiveAsync().WithCancellationTimeout(timeout); if (!result.RemoteEndPoint.Equals(dns)) { throw new IOException("Remote endpoint mismatch"); } byte[] buffer = result.Buffer; DefaultDnsResponse response = DefaultDnsResponse.FromArray(buffer); if (response.Truncated) { return(await fallback.Resolve(request)); } return(new ClientDnsResponse(request, response, buffer)); } }
public async Task <IDnsResponse> Resolve(IDnsRequest request) { using (TcpClient tcp = new TcpClient()) { await tcp.ConnectAsync(dns.Address, dns.Port); Stream stream = tcp.GetStream(); byte[] buffer = request.ToArray(); byte[] length = BitConverter.GetBytes((ushort)buffer.Length); if (BitConverter.IsLittleEndian) { Array.Reverse(length); } await stream.WriteAsync(length, 0, length.Length); await stream.WriteAsync(buffer, 0, buffer.Length); buffer = new byte[2]; await Read(stream, buffer); if (BitConverter.IsLittleEndian) { Array.Reverse(buffer); } buffer = new byte[BitConverter.ToUInt16(buffer, 0)]; await Read(stream, buffer); IDnsResponse response = DefaultDnsResponse.FromArray(buffer); return(new ClientDnsResponse(request, response, buffer)); } }
public Task <IDnsResponse> Resolve(IDnsRequest request) { IDnsResponse response = DefaultDnsResponse.FromRequest(request); foreach (DnsQuestion question in request.Questions) { IList <IResourceRecord> answers = Get(question); if (answers.Count > 0) { Merge(response.AnswerRecords, answers); } else { response.ResponseCode = DnsResponseCode.NameError; } } return(Task.FromResult(response)); }
private async void HandleRequest(byte[] data, IPEndPoint remote) { DefaultDnsRequest request = null; try { request = DefaultDnsRequest.FromArray(data); OnRequested(request); IDnsResponse response = await resolver.Resolve(request); OnResponded(request, response); await udp .SendAsync(response.ToArray(), response.Size, remote) .WithCancellationTimeout(UDP_TIMEOUT); } catch (SocketException e) { OnErrored(e); } catch (ArgumentException e) { OnErrored(e); } catch (IndexOutOfRangeException e) { OnErrored(e); } catch (OperationCanceledException e) { OnErrored(e); } catch (IOException e) { OnErrored(e); } catch (ObjectDisposedException e) { OnErrored(e); } catch (DnsResponseException e) { IDnsResponse response = e.DnsResponse; if (response == null) { response = DefaultDnsResponse.FromRequest(request); } try { await udp .SendAsync(response.ToArray(), response.Size, remote) .WithCancellationTimeout(UDP_TIMEOUT); } catch (SocketException) { } catch (OperationCanceledException) { } finally { OnErrored(e); } } }
public static ClientDnsResponse FromArray(IDnsRequest request, byte[] message) { DefaultDnsResponse response = DefaultDnsResponse.FromArray(message); return(new ClientDnsResponse(request, response, message)); }