private byte[] QueryByTcp(IPAddress nameServer, byte[] messageData, int messageLength, ref TcpClient tcpClient, ref NetworkStream tcpStream, out IPAddress responderAddress) { responderAddress = nameServer; IPEndPoint endPoint = new IPEndPoint(nameServer, _port); try { if (tcpClient == null) { tcpClient = new TcpClient(nameServer.AddressFamily) { ReceiveTimeout = QueryTimeout, SendTimeout = QueryTimeout }; tcpClient.Connect(endPoint); tcpStream = tcpClient.GetStream(); } int tmp = 0; byte[] lengthBuffer = new byte[2]; if (messageLength > 0) { DnsMessageBase.EncodeUShort(lengthBuffer, ref tmp, (ushort)messageLength); tcpStream.Write(lengthBuffer, 0, 2); tcpStream.Write(messageData, 0, messageLength); } lengthBuffer[0] = (byte)tcpStream.ReadByte(); lengthBuffer[1] = (byte)tcpStream.ReadByte(); tmp = 0; int length = DnsMessageBase.ParseUShort(lengthBuffer, ref tmp); byte[] resultData = new byte[length]; int readBytes = 0; while (readBytes < length) { readBytes += tcpStream.Read(resultData, readBytes, length - readBytes); } return(resultData); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); return(null); } }
private void TcpConnectCompleted <TMessage>(IAsyncResult ar) where TMessage : DnsMessageBase, new() { DnsClientAsyncState <TMessage> state = (DnsClientAsyncState <TMessage>)ar.AsyncState; if (state.Timer != null) { state.Timer.Dispose(); } if (state.TimedOut) { state.EndpointInfoIndex++; TcpBeginConnect(state); } else { try { state.TcpClient.EndConnect(ar); state.TcpStream = state.TcpClient.GetStream(); int tmp = 0; state.Buffer = new byte[2]; DnsMessageBase.EncodeUShort(state.Buffer, ref tmp, (ushort)state.QueryLength); IAsyncResult asyncResult = state.TcpStream.BeginWrite(state.Buffer, 0, 2, TcpSendLengthCompleted <TMessage>, state); state.Timer = new Timer(TcpTimedOut <TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); try { state.TcpClient.Close(); state.Timer.Dispose(); } catch { } state.EndpointInfoIndex++; TcpBeginConnect(state); } } }
internal void Encode(byte[] messageData, int offset, ref int currentPosition, Dictionary <string, ushort> domainNames) { DnsMessageBase.EncodeDomainName(messageData, offset, ref currentPosition, Name, true, domainNames); DnsMessageBase.EncodeUShort(messageData, ref currentPosition, (ushort)RecordType); DnsMessageBase.EncodeUShort(messageData, ref currentPosition, (ushort)RecordClass); }