如何获取特定ip的可用开放端口?

编程入门 行业动态 更新时间:2024-10-25 09:36:23
本文介绍了如何获取特定ip的可用开放端口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我提供客户端的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的可用开放端口?

本文发布于:2023-08-07 19:47:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1321409.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:端口   ip

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!