In C#, how to check if a TCP port is available?
Since you're using a TcpClient
, that means you're checking open TCP ports. There are lots of good objects available in the System.Net.NetworkInformation namespace.
Use the IPGlobalProperties
object to get to an array of TcpConnectionInformation
objects, which you can then interrogate about endpoint IP and port.
int port = 456; //<--- This is your value
bool isAvailable = true;
// Evaluate current system tcp connections. This is the same information provided
// by the netstat command line application, just in .Net strongly-typed object
// form. We will look through the list, and if our port we would like to use
// in our TcpClient is occupied, we will set isAvailable to false.
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
{
if (tcpi.LocalEndPoint.Port==port)
{
isAvailable = false;
break;
}
}
// At this point, if isAvailable is true, we can proceed accordingly.
c# Checking whether a port is actively listening?
You can run netstat -na
from command line to see all (including listening) ports.
If you add -b
you will also see linked executable to each connection/listening.
In .NET you can get all listening connections with System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()
C#: How to find an available port in a range of specific ports in TCP?
I found a way to perform that:
private static int initialPort = 6001; // initial port to search from
public static void StartServerTCP()
{
bool serverSet = false;
while (!serverSet && initialPort <= 7000)
{
try
{
Console.WriteLine(Dns.GetHostName() + ": (Server:TCP) Trying to setup server at port: {0} [TCP]", initialPort);
serverSocket.Bind(new IPEndPoint(GetIP(), initialPort));
serverSocket.Listen(0);
serverSocket.BeginAccept(AcceptCallback, null);
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(Dns.GetHostName() + ": (Server:TCP) Server setup completed at port {0} [TCP]\n", initialPort);
Console.ForegroundColor = ConsoleColor.Gray;
serverSet = true;
}
catch (Exception)
{
Console.WriteLine("\n" + Dns.GetHostName() + ": (Server:TCP) Port <{0}> is busy, trying a different one\n", initialPort);
initialPort++;
}
}
}
How to check remote IP and Port is available?
Use the Ping
class of .NET to find out if the system is up and connected, the use the PortScanner
to check if the port is open. check these links for further reading and exploring.
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping%28v=vs.110%29.aspx
http://social.msdn.microsoft.com/Forums/vstudio/en-US/8e4410bd-307f-4264-9575-cd9882653945/help-with-portscanner-in-c?forum=csharpgeneral
OR
public static bool PingHost(string hostUri, int portNumber)
{
try
{
using (var client = new TcpClient(hostUri, portNumber))
return true;
}
catch (SocketException ex)
{
MessageBox.Show("Error pinging host:'" + hostUri + ":" + portNumber.ToString() + "'");
return false;
}
}
Find the next TCP port in .NET
Here is what I was looking for:
static int FreeTcpPort()
{
TcpListener l = new TcpListener(IPAddress.Loopback, 0);
l.Start();
int port = ((IPEndPoint)l.LocalEndpoint).Port;
l.Stop();
return port;
}
Related Topics
How to Detect the Character Encoding of a Text File
Is There a Generic Constructor with Parameter Constraint in C#
How to Use Openfiledialog to Select a Folder
How to Run an Exe Program from a Windows Service Using C#
How to Serialize/Deserialize to 'Dictionary<Int, String>' from Custom Xml Not Using Xelement
.Net/C# - Convert Char[] to String
Omitting All Xsi and Xsd Namespaces When Serializing an Object in .Net
Asynchronous Locking Based on a Key
Adding Multiple Parameterized Variables to a Database in C#
Shorter Syntax for Casting from a List<X> to a List<Y>
Get Last 10 Lines of Very Large Text File > 10Gb
How to Force Garbage Collector to Run
A Field Initializer Cannot Reference the Non-Static Field, Method, or Property
What Is Hashcode Used For? Is It Unique
Change System Date Programmatically
How to Set Extended File Properties
Is the Order of Static Class Initialization in C# Deterministic