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);
try this, in my case the port number for the created object wasn't available so I came up with this
ipGlobalProperties.GetActiveTcpConnections()
doesn't return connections in Listen State.Port can be used for listening, but with no one connected to it the method described above will not work.
thanks for the answer jro. I had to tweak it for my usage. I needed to check if a port was being listened on, and not neccessarily active. For this I replaced
with
I iterated the array of endpoints checking that my port value was not found.
You have misunderstood what's happening here.
TcpClient(...) parameters are of server ip and server port you wish to connect to.
The TcpClient selects a transient local port from the available pool to communicate to the server. There's no need to check for the availability of the local port as it is automatically handled by the winsock layer.
In case you can't connect to the server using the above code fragment, the problem could be one or more of several. (i.e. server ip and/or port is wrong, remote server not available, etc..)
When you set up a TCP connection, the 4-tuple (source-ip, source-port, dest-ip, dest-port) has to be unique - this is to ensure packets are delivered to the right place.
There is a further restriction on the server side that only one server program can bind to an incoming port number (assuming one IP address; multi-NIC servers have other powers but we don't need to discuss them here).
So, at the server end, you:
On the client end, it's usually a little simpler:
There is no requirement that the destination IP/port be unique since that would result in only one person at a time being able to use Google, and that would pretty well destroy their business model.
This means you can even do such wondrous things as multi-session FTP since you set up multiple sessions where the only difference is your source port, allowing you to download chunks in parallel. Torrents are a little different in that the destination of each session is usually different.
And, after all that waffling (sorry), the answer to your specific question is that you don't need to specify a free port. If you're connecting to a server with a call that doesn't specify your source port, it'll almost certainly be using zero under the covers and the system will give you an unused one.