/// <summary>处理响应</summary> /// <param name="session"></param> /// <param name="request"></param> /// <param name="response"></param> protected virtual void Response(INetSession session, DNSEntity request, DNSEntity response) { var ss = session?.Session; if (ss == null) { return; } var isTcp = ss.Local.IsTcp; if (OnResponse != null) { var e = new DNSEventArgs { Request = request, Response = response, Session = ss }; OnResponse(this, e); } session?.Send(response.GetStream(isTcp)); }
/// <summary>异步查询解析</summary> /// <param name="dns"></param> /// <returns></returns> public virtual async Task <DNSEntity> QueryAsync(DNSEntity dns) { if (!Open()) { return(null); } var nc = Client; var tcs = new TaskCompletionSource <DNSEntity>(); _recv = tcs; // 发送请求 var ms = dns.GetStream(nc.Local.IsTcp); nc.Send(ms.ReadBytes()); Total++; return(await tcs.Task); }
internal DNSEntity Invoke(DNSEntity request, Boolean isQuery) { var attempts = 0; while (attempts <= _maxRetryAttemps) { var bytes = request.GetStream(false).ReadBytes(); if (bytes.Length > 512) { throw new ArgumentException("RFC 1035 2.3.4 states that the maximum size of a UDP datagram is 512 octets (bytes)."); } Socket socket = null; try { socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) { ReceiveTimeout = 300 }; //socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 300); socket.SendTo(bytes, bytes.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse("192.168.178.255"), 137)); if (!isQuery) { return(null); } // Messages carried by UDP are restricted to 512 bytes (not counting the IP // or UDP headers). Longer messages are truncated and the TC bit is set in // the header. (RFC 1035 4.2.1) var responseMessage = new Byte[512]; //int numBytes = socket.Receive(responseMessage); var ep = (EndPoint) new IPEndPoint(new IPAddress(4294967295), 137); var numBytes = socket.ReceiveFrom(responseMessage, ref ep); if (numBytes == 0 || numBytes > 512) { throw new Exception("RFC 1035 2.3.4 states that the maximum size of a UDP datagram is 512 octets (bytes)."); } //DnsReader br = new DnsReader(responseMessage); //DnsResponse res = new DnsResponse(br); var rs = DNSEntity.Read(responseMessage, false); if (request.Header.ID == rs.Header.ID) { return(rs); } attempts++; } catch { attempts++; } finally { socket.Close(); socket = null; } } throw new Exception("Could not resolve the query (" + attempts + " attempts)."); }