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);
You say
But you can always connect to a port while others are using it if something's listening there. Otherwise, http port 80 would be a mess.
If your
fails, then nothing's listening there. Otherwise, it will connect, even if some other machine/application has a socket open to that ip and port.
Thanks for this tip. I needed the same functionality but on the Server side to check if a Port was in use so I modified it to this code.
netstat! That's a network command line utility which ships with windows. It shows all current established connections and all ports currently being listened to. You can use this program to check, but if you want to do this from code look into the System.Net.NetworkInformation namespace? It's a new namespace as of 2.0. There's some goodies there. But eventually if you wanna get the same kind of information that's available through the command netstat you'll need to result to P/Invoke...
Update: System.Net.NetworkInformation
That namespace contains a bunch of classes you can use for figuring out things about the network.
I wasn't able to find that old pice of code but I think you can write something similar yourself. A good start is to check out the IP Helper API. Google MSDN for the GetTcpTable WINAPI function and use P/Invoke to enumerate until you have the information you need.
You don't have to know what ports are open on your local machine to connect to some remote TCP service (unless you want to use a specific local port, but usually that is not the case).
Every TCP/IP connection is identified by 4 values: remote IP, remote port number, local IP, local port number, but you only need to know remote IP and remote port number to establish a connection.
When you create tcp connection using
Your system will automatically assign one of many free local port numbers to your connection. You don't need to do anything. You might also want to check if a remote port is open. but there is no better way to do that than just trying to connect to it.