# how to detect Unity UNET errors?

I'm working on a simple multiplayer online game. and I use UNET and Networkmanager.

In my game I have some rooms and players that they can join to this rooms by connecting to specific server.exe file that I runned on a dedicated server.

My problem is when I use port 7777 for first server, if I run another server, then this error Appear :

Cannot open socket on ip{*},and port{7777}

For now I solved this issue by building servers with specific ports. for example in server1.exe I used port 7777 by default. and server2.exe , 7778 and same for other servers .

But I want to do this automatically. I mean when the server recognize port 7777 is busy , then increase port number.

I want to know can I use try catch for this kind of errors ? because I used try catch but it's not work. I don't know how to use it. this is part of my code :

try
{
StartServer();
}
catch(Exception ex)
{
networkPort++;
//then change port number and run server again
}


I just looking for a way that my servers run by choosing right port automatically.

• Sorry about that, I wasn't paying close enough attention to my browser tabs & gave a Java based answer (which doesn't apply to your situation) instead of a Unity/C# related one. – Pikalek Apr 18 '19 at 4:12

I solved my problem with another way that works very well.

For checking the port is free or not we can use System.Net.

and before Network Manager StartServer(), we have to check the current port is busy or not.

    int the_port = 7777;

IPEndPoint[] list_all_ports = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners();

foreach (IPEndPoint iep in list_all_ports)
{
if (the_port == iep.Port)
{
the_port++;
}
}

//set the network port
networkPort = the_port;
StartServer();


For example if another server use 7777 then new server port will set 7778 automatically.