Geekpedia Programming Tutorials






Creating a Port Scanner with C#

Learn how to create a simple port scanning tool in .NET, that allows you to scan IPs for open ports. It uses sockets that try to connect to the ports.

On Saturday, September 10th 2005 at 04:26 PM
By Andrew Pociu (View Profile)
*****   (Rated 4.4 with 26 votes)
Contextual Ads
More C# Resources
Advertisement
Download this Visual Studio 2005 project Download this project



An IP scanning tool can prove useful when you want to check the security of your computer. Having an open port doesn't necessarily mean an invitation to hackers because several applications and services use ports to communicate through the Internet. For example it's normal for a web server to have port 80 open, or for an FTP server to have port 21 open.



The way we're going to check for open parts might not be the fastest or most precise method, but it's the simplest. We're going to use a TcpClient to try and connect to each port. If the code raises an exception, it's probably because the connection was not successful. However, if there's no exception it means the TcpClient successfully connected to the port and thus the port is open.



First we need to use this using directive so we don't have to write really long lines of code:





using System.Net.Sockets;



Before implemeting a nice Windows Form where the user can input the IP and the port range to be scanned, let's hardcode the values to see how the scanning is actually done. Suppose we want to scan the ports from 1 to 25 for the IP 192.168.0.1 (a local network IP):





for (int CurrPort = 1; CurrPort <= 25; CurrPort++)

{

TcpClient TcpScan = new TcpClient();

try

{

// Try to connect

TcpScan.Connect("192.168.0.1", CurrPort);

// If there's no exception, we can say the port is open

MessageBox.Show("Port " + CurrPort + " open");

}

catch

{

// An exception occured, thus the port is probably closed

MessageBox.Show("Port " + CurrPort + " closed");

}

}



We loop from 1 to 25 (the ports) and try to connect, just like I explained earlier. That's all the code we need.

The Visual Studio 2005 project attached to this tutorial is a simple Windows Forms which you can see in the screenshot below:







The code for this application can be found in the click event of the Start Scan button (btnStart):





// Store values from the NumericUpDown to variables

StartPort = Convert.ToInt32(numStart.Value);

EndPort = Convert.ToInt32(numEnd.Value);

// Reset the progress bar

prgScanning.Value = 0;

// Set the max value of the progress bar

prgScanning.Maximum = EndPort - StartPort + 1;

// Let the user know the application is busy

Cursor.Current = Cursors.WaitCursor;

// Loop through the ports between start port and end port

for
(int CurrPort = StartPort; CurrPort <= EndPort; CurrPort++)

{

TcpClient TcpScan = new TcpClient();

try

{

// Try to connect

TcpScan.Connect(txtIP.Text, CurrPort);

// If there's no exception, we can say the port is open

txtLog.AppendText("Port " + CurrPort + " open");

}

catch

{

// An exception occured, thus the port is probably closed

txtLog.AppendText("Port " + CurrPort + " closed");

}

// Increase the progress on the progress bar

prgScanning.PerformStep();

}

// Set the cursor back to normal

Cursor.Current = Cursors.Arrow;
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by wombat on Wednesday, January 18th 2006 at 06:00 PM

No no no! Do not use try/catch blocks for branching purposes. Exceptions are for handling abnormal conditions _only_.

by XentriK on Friday, February 10th 2006 at 06:22 AM

yes its true wombat, its crashing ..:S

by Shabbir Kanchwala on Saturday, March 25th 2006 at 09:45 AM

Thats a awesome and very cool code

by Jay on Sunday, September 17th 2006 at 12:36 PM

Good Logic. But the TcpScan.Connect is just going to keep the underlying connection open and paves the way for the sneakers(hackers) to get in and play around. Needs to provide a way to close the underlying connection once the status of the ports are determined. If a closing logic is implemented TcpClient.Close() will not help. Refer to http://support.microsoft.com/default.aspx?scid=kb%3Ben-us%3B821625

by waqas hussain on Thursday, June 21st 2007 at 01:55 PM

is there any way to find the application which is using/listening the particular port?

by Usman Ajmal on Monday, October 29th 2007 at 09:41 AM

Is there any way to determine the name of service running on a closed port?

by quux on Saturday, February 16th 2008 at 11:55 PM

Just a note, the method shown can take 20 sec or so if there is no host, or if the host doesn\'t explicitly respond that the port is closed.

Here is what I used instead - I hope the formatting doesn\'t become mangled!

class PortScan //scans ports to see if they accept a connect
{
public static bool Connect(string IPAddress, int Port, int WaitSeconds)
{
TcpClient TcpScan = new TcpClient();
try
{
// Try to connect
bool ConnectSuccess = false;
TcpScan.BeginConnect(IPAddress, Port, null, null);
for (int i = 0; i <= WaitSeconds; i++) //wait specified # seconds for connection
{
System.Threading.Thread.Sleep(1000); //wait 1 sec
if (TcpScan.Connected)
{
ConnectSuccess = true;
break;
}
}
return ConnectSuccess;
// If there\'s no exception, we can say the port is open

}
catch
{
return false; // An exception occured, thus the port is probably closed
}
finally
{
TcpScan.Close(); //close the connection and socket
}
}
}

by TerryF. on Friday, March 14th 2008 at 09:01 PM

I am new to c# but would like to learn.
I would like to modify this code to "WATCH" a couple of ports for me... if any of them should close... I would like the program to run a series of batch (.bat) files. Can anyone point me in the right direction?
Thanks.

by wasantha on Saturday, June 28th 2008 at 04:31 PM

i wont port program tutorial

by james on Friday, July 11th 2008 at 09:02 AM

listen i am coding a tool and i put this in it i noticed some things it does not allow termintation of the scan

nor is the input validated for ipTxt which it should
not being a jerk ill fix it and post it but im having trouble getting it to stop what do i do to get the connection to close so i can put it behind a stop_scan button ?

by aree nadir on Saturday, July 19th 2008 at 11:36 AM

thanks for the program
i want to know more info about this code
does i can make by this program scanning for ports in every network or it must be local

by aree nadir on Saturday, July 19th 2008 at 11:36 AM

thanks for the program
i want to know more info about this code
does i can make by this program scanning for ports in every network or it must be local

by aree nadir on Saturday, July 19th 2008 at 11:36 AM

thanks for the program
i want to know more info about this code
does i can make by this program scanning for ports in every network or it must be local

by saijd on Monday, November 24th 2008 at 02:13 AM

This will close current client but not underlying connection.Is there any way to close underlying connection

by d0m14n on Thursday, January 29th 2009 at 10:53 AM

very cool dude this code needs some serious work ill fix it and repost it for one all fields need to be validated all input is malicious remember!!

and it needs to scan and close also needs error handling

by BAcid on Tuesday, March 17th 2009 at 09:42 PM

still waiting for the fixes....


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials
There are no related tutorials.

Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons