I am making a p2p program in c# and I would like to open up multiple instances of the program on my pc and connect them p2p over sockets. Each one should use a different port (if possible incremented by one). How could I accomplish this? The only thing I can think of is randomly generating them, but even so there could be two same ports. Thank you
When opening a socket with a port that is already in use, you get a socket exception. You can catch that exception and increase the port number. E.g. like this:
using System.Net;
using System.Net.Sockets;
public class PortOpener
{
private static Socket FindOpenPort(int startPort, int endport)
{
for (int port = startPort; port < endport; port++)
{
try
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(new IPEndPoint(IPAddress.Any, port));
return socket;
}
catch (SocketException ex)
{
if (ex.SocketErrorCode != SocketError.AddressAlreadyInUse) throw;
}
}
return null;
}
public static void Main()
{
var socket = FindOpenPort(8000, 8100);
}
}