SocketFactory.cs 5.3 KB

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