private void PrepareAndBindUdpSocket(DnsClientEndpointInfo endpointInfo, System.Net.Sockets.Socket udpClient) { if (endpointInfo.IsMulticast) { udpClient.Bind(new IPEndPoint(endpointInfo.LocalAddress, 0)); } else { udpClient.Connect(endpointInfo.ServerAddress, _port); } }
private void UdpBeginSend <TMessage>(DnsClientAsyncState <TMessage> state) where TMessage : DnsMessageBase, new() { if (state.EndpointInfoIndex == state.EndpointInfos.Count) { state.UdpClient = null; state.UdpEndpoint = null; state.SetCompleted(); return; } try { DnsClientEndpointInfo endpointInfo = state.EndpointInfos[state.EndpointInfoIndex]; state.UdpEndpoint = new IPEndPoint(endpointInfo.ServerAddress, _port); state.UdpClient = new System.Net.Sockets.Socket(state.UdpEndpoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp); PrepareAndBindUdpSocket(endpointInfo, state.UdpClient); state.TimedOut = false; state.TimeRemaining = QueryTimeout; IAsyncResult asyncResult = state.UdpClient.BeginSendTo(state.QueryData, 0, state.QueryLength, SocketFlags.None, state.UdpEndpoint, UdpSendCompleted <TMessage>, state); state.Timer = new Timer(UdpTimedOut <TMessage>, asyncResult, state.TimeRemaining, Timeout.Infinite); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); try { state.UdpClient.Close(); state.Timer.Dispose(); } catch {} state.EndpointInfoIndex++; UdpBeginSend(state); } }
private byte[] QueryByUdp(DnsClientEndpointInfo endpointInfo, byte[] messageData, int messageLength, out IPAddress responderAddress) { using (System.Net.Sockets.Socket udpClient = new System.Net.Sockets.Socket(endpointInfo.LocalAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp)) { try { udpClient.ReceiveTimeout = QueryTimeout; PrepareAndBindUdpSocket(endpointInfo, udpClient); EndPoint serverEndpoint = new IPEndPoint(endpointInfo.ServerAddress, _port); udpClient.SendTo(messageData, messageLength, SocketFlags.None, serverEndpoint); if (endpointInfo.IsMulticast) { serverEndpoint = new IPEndPoint(udpClient.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, _port); } byte[] buffer = new byte[65535]; int length = udpClient.ReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref serverEndpoint); responderAddress = ((IPEndPoint)serverEndpoint).Address; byte[] res = new byte[length]; Buffer.BlockCopy(buffer, 0, res, 0, length); return(res); } catch (Exception e) { Trace.TraceError("Error on dns query: " + e); responderAddress = default(IPAddress); return(null); } } }