如何获取特定ip的可用开放端口? [英] How to get the available open ports for particular ip?

查看:411
本文介绍了如何获取特定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的可用开放端口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆