2
0

SocketFactory.cs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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 Emby.Common.Implementations.Networking;
  8. using MediaBrowser.Model.Logging;
  9. using MediaBrowser.Model.Net;
  10. namespace Emby.Common.Implementations.Net
  11. {
  12. public class SocketFactory : ISocketFactory
  13. {
  14. // THIS IS A LINKED FILE - SHARED AMONGST MULTIPLE PLATFORMS
  15. // Be careful to check any changes compile and work for all platform projects it is shared in.
  16. // Not entirely happy with this. Would have liked to have done something more generic/reusable,
  17. // but that wasn't really the point so kept to YAGNI principal for now, even if the
  18. // interfaces are a bit ugly, specific and make assumptions.
  19. private readonly ILogger _logger;
  20. public SocketFactory(ILogger logger)
  21. {
  22. if (logger == null)
  23. {
  24. throw new ArgumentNullException("logger");
  25. }
  26. _logger = logger;
  27. }
  28. public ISocket CreateSocket(IpAddressFamily family, MediaBrowser.Model.Net.SocketType socketType, MediaBrowser.Model.Net.ProtocolType protocolType, bool dualMode)
  29. {
  30. try
  31. {
  32. var addressFamily = family == IpAddressFamily.InterNetwork
  33. ? AddressFamily.InterNetwork
  34. : AddressFamily.InterNetworkV6;
  35. var socket = new Socket(addressFamily, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
  36. if (dualMode)
  37. {
  38. socket.DualMode = true;
  39. }
  40. return new NetSocket(socket, _logger);
  41. }
  42. catch (SocketException ex)
  43. {
  44. if (dualMode)
  45. {
  46. _logger.Error("Error creating dual mode socket: {0}. Will retry with ipv4-only.", ex.SocketErrorCode);
  47. if (ex.SocketErrorCode == SocketError.AddressFamilyNotSupported)
  48. {
  49. return CreateSocket(IpAddressFamily.InterNetwork, socketType, protocolType, false);
  50. }
  51. }
  52. throw;
  53. }
  54. }
  55. #region ISocketFactory Members
  56. /// <summary>
  57. /// Creates a new UDP socket and binds it to the specified local port.
  58. /// </summary>
  59. /// <param name="localPort">An integer specifying the local port to bind the socket to.</param>
  60. public IUdpSocket CreateUdpSocket(int localPort)
  61. {
  62. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  63. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  64. try
  65. {
  66. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  67. return new UdpSocket(retVal, localPort, IPAddress.Any);
  68. }
  69. catch
  70. {
  71. if (retVal != null)
  72. retVal.Dispose();
  73. throw;
  74. }
  75. }
  76. /// <summary>
  77. /// Creates a new UDP socket that is a member of the SSDP multicast local admin group and binds it to the specified local port.
  78. /// </summary>
  79. /// <returns>An implementation of the <see cref="IUdpSocket"/> interface used by RSSDP components to perform socket operations.</returns>
  80. public IUdpSocket CreateSsdpUdpSocket(IpAddressInfo localIpAddress, int localPort)
  81. {
  82. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  83. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  84. try
  85. {
  86. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  87. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 4);
  88. var localIp = NetworkManager.ToIPAddress(localIpAddress);
  89. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse("239.255.255.250"), localIp));
  90. return new UdpSocket(retVal, localPort, localIp);
  91. }
  92. catch
  93. {
  94. if (retVal != null)
  95. retVal.Dispose();
  96. throw;
  97. }
  98. }
  99. /// <summary>
  100. /// Creates a new UDP socket that is a member of the specified multicast IP address, and binds it to the specified local port.
  101. /// </summary>
  102. /// <param name="ipAddress">The multicast IP address to make the socket a member of.</param>
  103. /// <param name="multicastTimeToLive">The multicast time to live value for the socket.</param>
  104. /// <param name="localPort">The number of the local port to bind to.</param>
  105. /// <returns></returns>
  106. public IUdpSocket CreateUdpMulticastSocket(string ipAddress, int multicastTimeToLive, int localPort)
  107. {
  108. if (ipAddress == null) throw new ArgumentNullException("ipAddress");
  109. if (ipAddress.Length == 0) throw new ArgumentException("ipAddress cannot be an empty string.", "ipAddress");
  110. if (multicastTimeToLive <= 0) throw new ArgumentException("multicastTimeToLive cannot be zero or less.", "multicastTimeToLive");
  111. if (localPort < 0) throw new ArgumentException("localPort cannot be less than zero.", "localPort");
  112. var retVal = new Socket(AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp);
  113. try
  114. {
  115. #if NETSTANDARD1_3
  116. // 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
  117. // See https://github.com/dotnet/corefx/pull/11509 for more details
  118. if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(System.Runtime.InteropServices.OSPlatform.Windows))
  119. {
  120. retVal.ExclusiveAddressUse = false;
  121. }
  122. #else
  123. retVal.ExclusiveAddressUse = false;
  124. #endif
  125. //retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
  126. retVal.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  127. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, multicastTimeToLive);
  128. var localIp = IPAddress.Any;
  129. retVal.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(ipAddress), localIp));
  130. retVal.MulticastLoopback = true;
  131. return new UdpSocket(retVal, localPort, localIp);
  132. }
  133. catch
  134. {
  135. if (retVal != null)
  136. retVal.Dispose();
  137. throw;
  138. }
  139. }
  140. #endregion
  141. }
  142. }