PDA

View Full Version : Port already being used by different client


taybill
07-15-2010, 05:37 PM
I am writing a client application.
The server can support only one client on a port. The last client who
made a connection "wins".

I want to avoid establishing a connection if another client (on the same machine I'm on) is already using the port.

Is there any way to determine if the port is already being used by a different client WITHOUT making a connection?

mjawwad
07-16-2010, 03:35 AM
You could try establishing a connection to the port and checking the error code.

using System.Net.Sockets;
using System.Net;

try
{
int port = 2000;
TcpClient client = new TcpClient(new IPEndPoint(IPAddress.Any, port));
}
catch (SocketException ex)
{
if (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)
{
Console.WriteLine("already in use");
}
throw ex;
}
catch (Exception e)
{

}