
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Use Sockets to Scan the Ports on a Machine
|
925
Solution
Use the CheapoPortScanner class constructed for your use; its code is shown in
Example 16-11.
CheapoPortScanner uses the Socket class to attempt to open a socket
and connect to an address on a given port. The
OpenPortFound event is available for a
callback when an open port is found in the range supplied to the
CheapoPortScanner
constructor or in the default range (1 to 65535). By default, CheapoPortScanner will
scan the local machine.
Example 16-11. CheapoPortScanner class
class CheapoPortScanner
{
#region Private consts and members
const int PORT_MIN_VALUE = 1;
const int PORT_MAX_VALUE = 65535;
private int _minPort = PORT_MIN_VALUE;
private int _maxPort = PORT_MAX_VALUE;
private List<int> _openPorts = null;
private List<int> _closedPorts = null;
private string _host = "127.0.0.1"; // localhost
#endregion
#region Event
public class OpenPortEventArgs : EventArgs
{
int _portNum;
public OpenPortEventArgs(int portNum) : base( )
{
_portNum = portNum;
}
public int PortNum
{
get { return _portNum; }
}
}
public delegate void OpenPortFoundEventHandler(object sender, OpenPortEventArgs args);
public event OpenPortFoundEventHandler OpenPortFound;
#endregion // Event
#region CTORs & Init code
public CheapoPortScanner( )
{
// Defaults are ...