2019-01-13 20:54:44 +01:00
|
|
|
using System;
|
2016-11-04 04:31:05 -04:00
|
|
|
using System.Net;
|
|
|
|
|
using System.Net.Sockets;
|
|
|
|
|
using MediaBrowser.Model.Net;
|
|
|
|
|
|
2017-08-16 02:43:41 -04:00
|
|
|
namespace Emby.Server.Implementations.Net
|
2016-11-04 04:31:05 -04:00
|
|
|
{
|
2023-10-11 00:02:37 +02:00
|
|
|
/// <summary>
|
|
|
|
|
/// Factory class to create different kinds of sockets.
|
|
|
|
|
/// </summary>
|
2016-11-04 04:31:05 -04:00
|
|
|
public class SocketFactory : ISocketFactory
|
|
|
|
|
{
|
2021-09-03 18:46:34 +02:00
|
|
|
/// <inheritdoc />
|
2023-02-16 18:15:12 +01:00
|
|
|
public Socket CreateUdpBroadcastSocket(int localPort)
|
2017-03-13 00:08:23 -04:00
|
|
|
{
|
2019-03-13 17:51:33 +01:00
|
|
|
if (localPort < 0)
|
|
|
|
|
{
|
|
|
|
|
throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
|
|
|
|
|
}
|
2017-03-13 00:08:23 -04:00
|
|
|
|
2023-02-16 18:15:12 +01:00
|
|
|
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
|
2017-03-13 00:08:23 -04:00
|
|
|
try
|
|
|
|
|
{
|
2023-02-16 18:15:12 +01:00
|
|
|
socket.EnableBroadcast = true;
|
|
|
|
|
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
|
|
|
|
|
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
|
|
|
|
|
socket.Bind(new IPEndPoint(IPAddress.Any, localPort));
|
2017-03-13 00:08:23 -04:00
|
|
|
|
2023-02-16 18:15:12 +01:00
|
|
|
return socket;
|
2017-03-13 00:08:23 -04:00
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
2023-10-08 00:46:15 +02:00
|
|
|
socket.Dispose();
|
2017-03-13 00:08:23 -04:00
|
|
|
|
|
|
|
|
throw;
|
|
|
|
|
}
|
|
|
|
|
}
|
2016-11-04 04:31:05 -04:00
|
|
|
}
|
|
|
|
|
}
|