SsdpHelper.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. namespace MediaBrowser.Dlna.Ssdp
  6. {
  7. public class SsdpHelper
  8. {
  9. private const string SsdpRenderer = "M-SEARCH * HTTP/1.1\r\n" +
  10. "HOST: 239.255.255.250:1900\r\n" +
  11. "User-Agent: UPnP/1.0 DLNADOC/1.50 Platinum/0.6.9.1\r\n" +
  12. "ST: urn:schemas-upnp-org:device:MediaRenderer:1\r\n" +
  13. "MAN: \"ssdp:discover\"\r\n" +
  14. "MX: {0}\r\n" +
  15. "\r\n";
  16. /// <summary>
  17. /// Creates a SSDP MSearch packet for DlnaRenderers.
  18. /// </summary>
  19. /// <param name="mx">The mx. (Delaytime for device before responding)</param>
  20. /// <returns></returns>
  21. public static byte[] CreateRendererSSDP(int mx)
  22. {
  23. return Encoding.UTF8.GetBytes(string.Format(SsdpRenderer, mx));
  24. }
  25. /// <summary>
  26. /// Parses the socket response into a location Uri for the DeviceDescription.xml.
  27. /// </summary>
  28. /// <param name="data">The data.</param>
  29. /// <returns></returns>
  30. public static Dictionary<string,string> ParseSsdpResponse(byte[] data)
  31. {
  32. var headers = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  33. using (var reader = new StreamReader(new MemoryStream(data), Encoding.ASCII))
  34. {
  35. for (var line = reader.ReadLine(); line != null; line = reader.ReadLine())
  36. {
  37. line = line.Trim();
  38. if (string.IsNullOrEmpty(line))
  39. {
  40. break;
  41. }
  42. var parts = line.Split(new[] { ':' }, 2);
  43. if (parts.Length == 2)
  44. {
  45. headers[parts[0]] = parts[1].Trim();
  46. }
  47. }
  48. }
  49. return headers;
  50. }
  51. }
  52. }