Click here to Skip to main content
15,888,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to list out all open ports of the system from C#3.0.It should fast

I am trying by this code but it is very slow
C#
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"); 
  }
}
Posted
Updated 10-Aug-12 8:28am
v2
Comments
Philip Stuyck 10-Aug-12 13:56pm    
TCP or UDP ?
Gajendra Yadav 10-Aug-12 14:13pm    
Both protocol
[no name] 10-Aug-12 14:09pm    
What is the problem? What have you tried? Where is the code that demonstrates your problem?
Gajendra Yadav 10-Aug-12 14:23pm    
I am trying by this code but it is very slow
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");

}

}
[no name] 10-Aug-12 14:30pm    
Define "slow". How did you measure the time? How many iterations did you measure? How fast do you think it should be? Did you profile your code?

1 solution

Port scanners usually scan in parallel so you can do the following (.net 4):
C#
List<Task> tasks = new List<Task>();

for(int i =1;i<65535;i++)
{
    Task t = Task.Factory.StartNew( () => portscan(i));
    tasks.Add(t);
}

Task.WaitAll(tasks.ToArray());
 
Share this answer
 
v2
Comments
Gajendra Yadav 12-Aug-12 10:41am    
This solution is nice but i want in .net 3.5.
Mehdi Gholam 12-Aug-12 11:18am    
You can use a ThreadPool : http://msdn.microsoft.com/en-us/library/3dasc8as%28v=vs.80%29.aspx

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900