ServerDiscovery.cs 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. namespace MediaBrowser.ApiInteraction
  7. {
  8. public static class ServerDiscovery
  9. {
  10. /// <summary>
  11. /// Attemps to discover the server within a local network
  12. /// </summary>
  13. public static async Task<IPEndPoint> DiscoverServer()
  14. {
  15. // Create a udp client
  16. var client = new UdpClient(new IPEndPoint(IPAddress.Any, GetRandomUnusedPort()));
  17. // Construct the message the server is expecting
  18. var bytes = Encoding.UTF8.GetBytes("who is MediaBrowserServer?");
  19. // Send it - must be IPAddress.Broadcast, 7359
  20. var targetEndPoint = new IPEndPoint(IPAddress.Broadcast, 7359);
  21. // Send it
  22. await client.SendAsync(bytes, bytes.Length, targetEndPoint).ConfigureAwait(false);
  23. // Get a result back
  24. var result = await client.ReceiveAsync().ConfigureAwait(false);
  25. if (result.RemoteEndPoint.Port == targetEndPoint.Port)
  26. {
  27. // Convert bytes to text
  28. var text = Encoding.UTF8.GetString(result.Buffer);
  29. // Expected response : MediaBrowserServer|192.168.1.1:1234
  30. // If the response is what we're expecting, proceed
  31. if (text.StartsWith("mediabrowserserver", StringComparison.OrdinalIgnoreCase))
  32. {
  33. text = text.Split('|')[1];
  34. var vals = text.Split(':');
  35. return new IPEndPoint(IPAddress.Parse(vals[0]), int.Parse(vals[1]));
  36. }
  37. }
  38. return null;
  39. }
  40. /// <summary>
  41. /// Gets a random port number that is currently available
  42. /// </summary>
  43. private static int GetRandomUnusedPort()
  44. {
  45. var listener = new TcpListener(IPAddress.Any, 0);
  46. listener.Start();
  47. var port = ((IPEndPoint)listener.LocalEndpoint).Port;
  48. listener.Stop();
  49. return port;
  50. }
  51. }
  52. }