Reputation: 2809
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.
Upvotes: 2
Views: 7300
Reputation: 3439
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)
{
...
}
Upvotes: 4
Reputation: 223392
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
Upvotes: 5
Reputation: 950
Use try-catch blocks and catch the SocketException.
try
{
//Code here
}
catch (SocketException ex)
{
//Handle exception here
}
Upvotes: 2
Reputation: 70776
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());
}
Upvotes: 2
Reputation: 62265
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.
Upvotes: 1
Reputation: 46008
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
}
Upvotes: 3