In C# to use a TcpClient or generally to connect to a socket how can I first check if a certain port is free on my machine?
more info: This is the code I use:
TcpClient c;
//I want to check here if port is free.
c = new TcpClient(ip, port);
In C# to use a TcpClient or generally to connect to a socket how can I first check if a certain port is free on my machine?
more info: This is the code I use:
TcpClient c;
//I want to check here if port is free.
c = new TcpClient(ip, port);
If I'm not very much mistaken, you can use System.Network.whatever to check.
However, this will always incur a race condition.
The canonical way of checking is try to listen on that port. If you get an error that port wasn't open.
I think this is part of why bind() and listen() are two separate system calls.
From the avalaible ports i would exclude:
With the following import:
You can use the following function to check if a port is avalaible or not:
I give you a similar function for those who use VB.NET:
Check for error code 10048
You're on the wrong end of the Intertube. It is the server that can have only one particular port open. Some code:
Fails with:
Be aware the time window between you make check and the moment you try to make connection some process may take the port - classical TOCTOU. Why don't you just try to connect? If it fails then you know the port is not 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 ofTcpConnectionInformation
objects, which you can then interrogate about endpoint IP and port.