domingo, 27 de diciembre de 2009

port scanner usando la Task Parallel Library

Poderoza la Task Parallel Library, dejo un ejemplo bastante simple de un port scanner que hace su trabajo en paralelo pero sin crear un solo thread en forma explícita. Toda la magia está en:

Parallel.For(from, to, (port) => {});



class Program
{
static void Main(string[] args)
{
if (args.Length < 2 || args.Length > 3)
throw new ArgumentException();

var to = 0;
var from = 0;
var host = args[0];

#region argument validation
//...
#endregion

Console.WriteLine("Scanning {0} ports from: {1} to {2}", host, from, to - 1);

// parallel port scan
Parallel.For(from, to, (port) =>
{
var tcpScan = new TcpClient();

try
{
tcpScan.Connect(host, port);

if (tcpScan.Connected)
Console.WriteLine("Listening on port: {0}", port);
}
catch (Exception)
{
}
finally
{
if (tcpScan.Connected)
tcpScan.Close();
}
});

Console.ReadKey();
}
}

1 comentario:

Anónimo dijo...

A SUPPORTED BY THE DEVELOPER TOOLS? It was interesting. You seem very knowledgeable in ypour field.

rH3uYcBX