2

I create a TCP listener by using the code below:

TCPListener = new TcpListener(IPAddress.Any, 1234);

I start to listen TCP devices by using the code below:

TCPListener.Start();

But here, i don't control if the port is in use. When the port is in use, program gives an exception: "Only one usage of each socket address (protocol/network address/port) is normally permitted.".

How do i handle this exception? I want to warn user that the port is in use.

Darren
  • 68,902
  • 24
  • 138
  • 144
sanchop22
  • 2,729
  • 12
  • 43
  • 66

6 Answers6

5

Put a try/catch block around TCPListener.Start(); and catch SocketException. Also if you are opening multiple connections from your program, then its better if you keep track of your connections in a list and before opening a connection see if you already have a connection opened

Habib
  • 219,104
  • 29
  • 407
  • 436
4

It's not a good idea to get an exception to check whether the port is in use or not. Use the IPGlobalProperties object to get to an array of TcpConnectionInformation objects, which you can then interrogate about endpoint IP and port.

 int port = 1234; //<--- This is your value
 bool isAvailable = true;

 // Evaluate current system tcp connections. This is the same information provided
 // by the netstat command line application, just in .Net strongly-typed object
 // form.  We will look through the list, and if our port we would like to use
 // in our TcpClient is occupied, we will set isAvailable to false.
 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
 TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

 foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
 {
   if (tcpi.LocalEndPoint.Port==port)
   {
     isAvailable = false;
     break;
   }
 }

 // At this point, if isAvailable is true, we can proceed accordingly.

For details please read this.

For handling the exception you will use try/catch as habib suggested

try
{
  TCPListener.Start();
}
catch(SocketException ex)
{
  ...
}
Community
  • 1
  • 1
ABH
  • 3,391
  • 23
  • 26
3

Catch it and display your own error message.

Check the exception type and use this type in catch clause.

try
{
  TCPListener.Start();
}
catch(SocketException)
{
  // Your handling goes here
}
Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
2

Put it in a try catch block.

try {
   TCPListener = new TcpListener(IPAddress.Any, 1234);
   TCPListener.Start();

} catch (SocketException e) {
  // Error handling routine
   Console.WriteLine( e.ToString());
 }
Darren
  • 68,902
  • 24
  • 138
  • 144
2

Use try-catch blocks and catch the SocketException.

try
{
  //Code here
}
catch (SocketException ex)
{
  //Handle exception here
}
Chris Dworetzky
  • 940
  • 4
  • 9
1

Well, considering that you're talking about exceptional situation, just handle that exception with suitable try/catch block, and inform a user about a fact.

Tigran
  • 61,654
  • 8
  • 86
  • 123