Friday, 9 October 2009

How to Know Which Ports of a Computer Is Open or Closed?

Code:

This is my PortScanner class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;

public class PortScanner
{
public string Host { get; set; }

public PortScanner(string host)
{
this.Host = host;
}

public ScannerResult Scan(int fromPort, int toPort)
{
var result = new ScannerResult();

for (int portNumber = fromPort; portNumber <= toPort; portNumber++)
{
if (IsPortOpen(portNumber))
result.OpenPorts.Add(portNumber.ToString());

else result.ClosedPorts.Add(portNumber.ToString());
}

return result;
}

public int FindFirstOpenPort(int fromPort, int toPort)
{
for (int portNumber = fromPort; portNumber <= toPort; portNumber++)
{
if (IsPortOpen(portNumber))
return portNumber;
}
return 0;
}







private static int FindFreePort()
{
int port = 0;

IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
socket.Bind(endPoint);
IPEndPoint local = (IPEndPoint)socket.LocalEndPoint;
port = local.Port;
}

if (port == 0)
throw new InvalidOperationException("Unable to find a free port.");

return port;
}

public bool IsPortOpen(int port)
{
Socket socket = null;
try
{
// Make a TCP-based socket
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
// Connect
socket.Connect(host, port);
return true;
}
catch (SocketException se)
{
if (se.SocketErrorCode == SocketError.ConnectionRefused)
{
return false;
}
else
{
// An error occurred when attempting to access the socket
Debug.WriteLine(se.ToString());
Console.WriteLine(se.ToString());
}
}
finally
{
if (socket != null)
{
if (socket.Connected)
socket.Disconnect(false);
socket.Close();
}
}
return false;
}

}








This is my ScannerResult class:






using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class ScannerResult
{
public List<string> OpenPorts = new List<string>();
public List<string> ClosedPorts = new List<string>();
}




And this is how to use it:




var portScanner = new PortScanner("127.0.0.1");
var result = portScanner.Scan(1, 65535);

No comments: