private static async Task CheckPortTcp(IPAddress ipAddr, int port, int timeout = 2000) { using (var tcpClient = new TcpClient()) { var connectTask = await tcpClient.ConnectAsync(ipAddr, port, timeout); PortStatus portStatus; switch (connectTask.Status) { case TaskStatus.RanToCompletion: portStatus = PortStatus.OPEN; break; case TaskStatus.Faulted: portStatus = PortStatus.CLOSED; break; default: portStatus = PortStatus.FILTERED; break; } ProtocolType?protocolType = null; if (portStatus == PortStatus.OPEN) { var data = new byte[256]; using (var stream = tcpClient.GetStream()) { stream.ReadTimeout = timeout; stream.WriteTimeout = timeout; var writeTask = stream.WriteAsync(PacketToSend, 0, PacketToSend.Length); var readTask = stream.ReadAsync(data, 0, data.Length); try { await writeTask; } catch (Exception e) { //Console.WriteLine(e.Message); } if (writeTask.Status == TaskStatus.RanToCompletion) { try { await readTask; } catch (Exception e) { //Console.WriteLine(e.Message); } if (readTask.Status == TaskStatus.RanToCompletion) { var length = readTask.Result; data = data.Take(length).ToArray(); protocolType = ProtocolCheckingUtils.DetectProtocol(data); } } } Console.WriteLine($"TCP {port} {protocolType}"); } } }
private static async Task CheckPortUdp(IPAddress ipAddr, int port, int timeout = 2000) { using (var udpClient = new UdpClient()) { var connectTask = udpClient.Client.ConnectAsync(ipAddr, port); PortStatus portStatus; ProtocolType?protocolType = null; await Task.WhenAny(Task.Delay(timeout), connectTask); if (connectTask.IsCompleted && connectTask.Exception != null && connectTask.Exception.InnerExceptions .Where(x => x is SocketException) .Any(x => ((SocketException)x).ErrorCode == 10054)) //WSAECONNRESET { portStatus = PortStatus.CLOSED; } else { portStatus = PortStatus.OPEN; } if (portStatus == PortStatus.OPEN) { var writeTask = udpClient.SendAsync(PacketToSend, PacketToSend.Length); var readTask = udpClient.ReceiveAsync(); try { await Task.WhenAny(writeTask, Task.Delay(timeout)); } catch (Exception e) { //Console.WriteLine(e); } if (writeTask.Status == TaskStatus.RanToCompletion) { try { await Task.WhenAny(readTask, Task.Delay(timeout)); } catch (Exception e) { //Console.WriteLine(e); } if (readTask.Status == TaskStatus.RanToCompletion) { protocolType = ProtocolCheckingUtils.DetectProtocol(readTask.Result.Buffer); } else { return; } } else { return; } Console.WriteLine($"UDP {port} {protocolType}"); } } }