当我提供客户端的IP地址时,我必须知道客户端的可用开放端口。比如当我们提供客户端的IP地址时,它会扫描客户端的可用端口。 我尝试过: 使用System; 使用System.Collections.Generic; 使用System.Linq; 使用System.Text; 使用System.Net.Sockets; 使用System.Threading; 使用System.Net; 名称空间SimplePortScan { 公共类PortScanner { 私有IP地址_target; public int Port {get;私人集; } public bool IsOpen {get;私人集; } $ / $ 公共PortScanner(IPAddress目标,int端口) { _target = target; 端口=端口; } public void ScanPort() { 使用(TcpClient TcpClient = new TcpClient()) { 试试 { TcpClient.Connect(_target,Port); } catch(SocketException) { IsOpen =假; } if(IsOpen) { 使用( NetworkStream ClientStream = TcpClient.GetStream()) { IsOpen = true; } } } } } }
when I give the ip address of the client I have to know the available open ports of the client. like when we give the ip address of the client it will scan the available ports of the client. What I have tried: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net.Sockets; using System.Threading; using System.Net; namespace SimplePortScan { public class PortScanner { private IPAddress _target; public int Port { get; private set; } public bool IsOpen { get; private set; } public PortScanner(IPAddress target, int port) { _target = target; Port = port; } public void ScanPort() { using (TcpClient TcpClient = new TcpClient()) { try { TcpClient.Connect(_target, Port); } catch (SocketException) { IsOpen = false; } if (IsOpen) { using (NetworkStream ClientStream = TcpClient.GetStream()) { IsOpen = true; } } } } } }
推荐答案using System; using System.Net.Sockets; using System.Threading.Tasks; namespace TestApps { internal class Program { private static void Main(string[] args) { const string ipAddress = "192.168.1.2"; const int fromPort = 1; const int toPort = 50; Parallel.For(fromPort, toPort, port => { var isPortOpen = IsPortOpen(ipAddress, port); Console.WriteLine(isPortOpen ? "{0} : open" : "{0} : close", port); }); } private static bool IsPortOpen(string ipAddress, int port) { var tcpClient = new TcpClient(); try { var result = tcpClient.BeginConnect(ipAddress, port, null, null); var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1)); tcpClient.EndConnect(result); tcpClient.Close(); return success; } catch { return false; } } } }
更多推荐
如何获取特定ip的可用开放端口?
发布评论