views:

23

answers:

1

I need to establish a TCP connection with a remote machine, but before I do that, I need to detect, if the port is in use by another application (if there is already one connection on this port). In other words I want to ensure that only one application is using the same port a time.

What is the way to do it in .NET?

A: 

What do you mean by another application? The client can connect to a remote server port and if there's nothing listening to this port TcpClient will throw an exception. So attempt to connect and catch the exception. If the server application listening on this port doesn't talk the same protocol as the client an exception will be thrown when you try to send and read the data as it won't conform. All these are exceptional cases.

Darin Dimitrov
Another application, is another client which is already using this port (most likely it will be running on another machine). The problem is that I want to have exclusively one connection to the server and if there is a connection already I want my application to prompt the user about it.
Vitalij
This needs to be handled by the server. There's nothing at the TCP level which prevents multiple clients connecting to a listening port. So the server needs to keep track of clients and if there's more than one client either drop the connection or send some info to the client informing him that another client is already connected. All this will depend of course on the protocol you are using.
Darin Dimitrov
The problem is that the server is a doesn't stop you from connecting more than one clients. And this is not a standard server client application, in terms that my server is a pump controller. And I can't change neither the protocols nor the the server implementation.
Vitalij
@Vitalij: Then you're SOL :) - unless you can introduce a proxy that does the limiting.
snemarch