2
0

SocketFactory.cs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Sockets;
  6. using System.Threading.Tasks;
  7. using MediaBrowser.Model.Net;
  8. namespace Emby.Common.Implementations.Net
  9. {
  10. public class SocketFactory : ISocketFactory
  11. {
  12. // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
  13. // Be careful to check any changes compile and work for all platform projects it is shared in.
  14. // Not entirely happy with this. Would have liked to have done something more generic/reusable,
  15. // but that wasn't really the point so kept to YAGNI principal for now, even if the
  16. // interfaces are a bit ugly, specific and make assumptions.
  17. /// <summary>
  18. /// Used by RSSDP components to create implementations of the <see cref="IUdpSocket"/> interface, to perform platform agnostic socket communications.
  19. /// </summary>
  20. private IPAddress _LocalIP;
  21. /// <summary>
  22. /// Default constructor.
  23. /// </summary>
  24. /// <param name="localIP">A string containing the IP address of the local network adapter to bind sockets to. Null or empty string will use <see cref="IPAddress.Any"/>.</param>
  25. public SocketFactory(string localIP)
  26. {
  27. if (String.IsNullOrEmpty(localIP))
  28. _LocalIP = IPAddress.Any;
  29. else
  30. _LocalIP = IPAddress.Parse(localIP);
  31. }
  32. #region ISocketFactory Members
  33. /// <summary>
  34. /// Creates a new UDP socket that is a member of the SSDP multicast local admin group and binds it to the specified local port.
  35. /// </summary>
  36. /// <param name="localPort">An integer specifying the local port to bind the socket to.</param>
  37. /// <returns>An implementation of the <see cref="IUdpSocket"/> interface used by RSSDP components to perform socket operations.</returns>
  38. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The purpose of this method is to create and returns a disposable result, it is up to the caller to dispose it when they are done with it.")]
  39. public IUdpSocket CreateUdpSocket(int localPort)
  40. {
  41. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  42. var retVal = new Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  43. try
  44. {
  45. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  46. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  47. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), _LocalIP));
  48. return new UdpSocket(retVal, localPort, _LocalIP.ToString());
  49. }
  50. catch
  51. {
  52. if (retVal != null)
  53. retVal.Dispose();
  54. throw;
  55. }
  56. }
  57. /// <summary>
  58. /// Creates a new UDP socket that is a member of the specified multicast IP address, and binds it to the specified local port.
  59. /// </summary>
  60. /// <param name="ipAddress">The multicast IP address to make the socket a member of.</param>
  61. /// <param name="multicastTimeToLive">The multicast time to live value for the socket.</param>
  62. /// <param name="localPort">The number of the local port to bind to.</param>
  63. /// <returns></returns>
  64. [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "ip"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "The purpose of this method is to create and returns a disposable result, it is up to the caller to dispose it when they are done with it.")]
  65. public IUdpSocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
  66. {
  67. if (ipAddress == null) throw new ArgumentNullException("ipAddress");
  68. if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", "ipAddress");
  69. if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", "multicastTimeToLive");
  70. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  71. var retVal = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  72. try
  73. {
  74. #if NETSTANDARD1_3
  75. // The ExclusiveAddressUse socket option is a Windows-specific option that, when set to "true," tells Windows not to allow another socket to use the same local address as this socket
  76. // See https://github.com/dotnet/corefx/pull/11509 for more details
  77. if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
  78. {
  79. retVal.ExclusiveAddressUse = false;
  80. }
  81. #else
  82. retVal.ExclusiveAddressUse = false;
  83. #endif
  84. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  85. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
  86. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAddress), _LocalIP));
  87. retVal.MulticastLoopback = true;
  88. return new UdpSocket(retVal, localPort, _LocalIP.ToString());
  89. }
  90. catch
  91. {
  92. if (retVal != null)
  93. retVal.Dispose();
  94. throw;
  95. }
  96. }
  97. #endregion
  98. }
  99. }