Search code examples
c#remotingclient-serverservice-discovery

What is the best way for a client app to find a server on a local network in C#?


The client connects to the server using GenuineChannels (we are considering switching to DotNetRemoting). What I mean by find is obtain the IP and port number of a server to connect to.

It seems like a brute-force approach would be try every IP on the network try the active ports (not even sure if that's possible) but there must be a better way.


Solution

  • Consider broadcasting a specific UDP packet. When the server or servers see the broadcasted UDP packet they send a reply. The client can collect the replies from all the servers and start connecting to them or based on an election algorithm.

    See example for client (untested code):


    using System.Net;
    using System.Net.Sockets;
    
    [STAThread]
    static void Main(string[] args)
    {
        Socket socket = new Socket(AddressFamily.InterNetwork,
        SocketType.Dgram, ProtocolType.Udp);
        socket.Bind(new IPEndPoint(IPAddress.Any, 8002));
        socket.Connect(new IPEndPoint(IPAddress.Broadcast, 8001));
        socket.Send(System.Text.ASCIIEncoding.ASCII.GetBytes("hello"));
    
        int availableBytes = socket.Available;
        if (availableBytes > 0)
        {
            byte[] buffer = new byte[availableBytes];
            socket.Receive(buffer, 0, availableBytes, SocketFlags.None);
            // buffer has the information on how to connect to the server
        }
    }