2
0

SocketFactory.cs 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. using System;
  2. using System.Net;
  3. using System.Net.Sockets;
  4. using MediaBrowser.Model.Net;
  5. namespace Emby.Server.Implementations.Net
  6. {
  7. /// <summary>
  8. /// Factory class to create different kinds of sockets.
  9. /// </summary>
  10. public class SocketFactory : ISocketFactory
  11. {
  12. /// <inheritdoc />
  13. public Socket CreateUdpBroadcastSocket(int localPort)
  14. {
  15. if (localPort < 0)
  16. {
  17. throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
  18. }
  19. var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
  20. try
  21. {
  22. socket.EnableBroadcast = true;
  23. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
  24. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  25. socket.Bind(new IPEndPoint(IPAddress.Any, localPort));
  26. return socket;
  27. }
  28. catch
  29. {
  30. socket.Dispose();
  31. throw;
  32. }
  33. }
  34. }
  35. }