Search code examples
c#.netnetwork-programmingmauiiot

How to brodcast discover a webserver on a special port


I have a webserver running on a raspberry pi on port 7299, and I also have a .NET MAUI app which I want to discover the raspberry pi webserver from. The raspberry is kind of an IoT where I want to exchange some data between, how can I discover the device in a smart and fast way?

I have tried googling around and asked GPT, but I cannot figure out a smart way. I first tried a for loop with all the addresses in the network, but its really slow. I read somewhere that you maybe could do a "brodcast" and discover the device but I cannot figure out how to do it.

If it helps the webserver on the raspberry pi is running a docker container with a .NET MVC/API project.

Thanks for all ideas and help!

Best regards Max


Solution

  • I solved it the best way I could, and I think it works pretty fast, this is my current solution if no one else has a better idea:

    public async Task DiscoverDeviceAsync()
            {
                string networkRange = "10.10.0.1-10.10.0.254"; 
                int port = 7299; 
    
                string[] ipRange = networkRange.Split('-');
                IPAddress startIPAddress = IPAddress.Parse(ipRange[0]);
                IPAddress endIPAddress = IPAddress.Parse(ipRange[1]);
    
                var tasks = new Task[endIPAddress.GetAddressBytes()[3] - startIPAddress.GetAddressBytes()[3] + 1];
    
                for (int i = 0; i < tasks.Length; i++)
                {
                    byte[] ipBytes = startIPAddress.GetAddressBytes();
                    ipBytes[3] += (byte)i;
                    IPAddress currentIPAddress = new(ipBytes);
                    tasks[i] = ScanIPAddress(currentIPAddress, port);
                }
    
                await Task.WhenAll(tasks);
            }
    
            async Task ScanIPAddress(IPAddress ipAddress, int port)
            {
                try
                {
                    using TcpClient tcpClient = new();
                    tcpClient.SendTimeout = 100;
                    await tcpClient.ConnectAsync(ipAddress, port);
                    Console.WriteLine($"Web server found at IP address: {ipAddress}");
                    WebServerIp = ipAddress.ToString();
                }
                catch (SocketException ex)
                {
                    Console.WriteLine(ex);
                }
            }