Search code examples
c#.netdevice-discovery

Discovery in c#


I've to implement some discovery for an internal solution.

We have two kind of software:

  • Server: They manage a lot of hardware devices and can give access to some data (.Net remoting)
  • Client: They can display data of one or several Server(graphs, stats, ...)

Currently we are setting the IP by hand on the client.

We would like to implement a discovery.

We have the following requirement:

  • It has to be usable in c#
  • When a server is up, it must be displayed as available very fastly
  • Same when it shut down
  • If the server doesn't stops in a clean way, we can have a way to detect it(no need to be very fast, can be done every 10-15min).
  • It can give me some information(Server version, port to use, ...)
  • We have client computer with multiple network cards, we must discover server on each cards

Do you have a protocol, a library, ... to advice?

We tried UPnP, but seems there is no good Server+client implementation in c# that meet our requirement


Solution

  • Use UDP broadcasts from the discovering app (client):

    int broadcastPort = //something
    byte[] msg = //something
    
    //Cycle this for all IP adresses
    IPAddress broadcastIp = //Broadcast address for this net
    IPEndPoint destinationEndpoint = new IPEndPoint(broadcastIp, broadcastPort);
    Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
    sock.SendTo(msg, broadcastEndpoint);
    

    And have the discovered app (Server) answer, to receive the answer use UdpClient.Receive(), which gives you the IP of the answering station.