aboutsummaryrefslogtreecommitdiff
path: root/Emby.Server.Implementations/Net/SocketFactory.cs
blob: a3484f43e9d2e91ba1aa2387c290063ab6caf03b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using System;
using System.Net;
using System.Net.Sockets;
using MediaBrowser.Model.Net;

namespace Emby.Server.Implementations.Net
{
    /// <summary>
    /// Factory class to create different kinds of sockets.
    /// </summary>
    public class SocketFactory : ISocketFactory
    {
        /// <inheritdoc />
        public Socket CreateUdpBroadcastSocket(int localPort)
        {
            if (localPort < 0)
            {
                throw new ArgumentException("localPort cannot be less than zero.", nameof(localPort));
            }

            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            try
            {
                socket.EnableBroadcast = true;
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                socket.Bind(new IPEndPoint(IPAddress.Any, localPort));

                return socket;
            }
            catch
            {
                socket.Dispose();

                throw;
            }
        }
    }
}