Skip to content

Commit

Permalink
fix(MulticastClient): do not leak UdpClients
Browse files Browse the repository at this point in the history
  • Loading branch information
richardschneider committed Dec 13, 2018
1 parent 8f7a766 commit 65e8e68
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions src/MulticastClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using Common.Logging;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -11,6 +12,7 @@ namespace Makaretu.Dns
{
class MulticastClient : IDisposable
{
static readonly ILog log = LogManager.GetLogger(typeof(MulticastClient));
public static readonly bool IP6;

readonly IPEndPoint multicastEndpoint;
Expand Down Expand Up @@ -38,13 +40,20 @@ public MulticastClient(IPEndPoint multicastEndpoint, IEnumerable<NetworkInterfac

foreach (var address in nics.SelectMany(GetNetworkInterfaceLocalAddresses))
{
if (senders.Keys.Contains(address))
{
continue;
}

var localEndpoint = new IPEndPoint(address, multicastEndpoint.Port);
log.Debug($"Will send to {localEndpoint}");
var sender = new UdpClient(multicastEndpoint.AddressFamily);
try
{
receiver.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastEndpoint.Address, address));

var sender = new UdpClient(multicastEndpoint.AddressFamily);
sender.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
sender.Client.Bind(new IPEndPoint(address, multicastEndpoint.Port));
sender.Client.Bind(localEndpoint);
sender.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastEndpoint.Address));
sender.Client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, true);

Expand All @@ -57,6 +66,12 @@ public MulticastClient(IPEndPoint multicastEndpoint, IEnumerable<NetworkInterfac
catch (SocketException ex) when (ex.SocketErrorCode == SocketError.AddressNotAvailable)
{
// VPN NetworkInterfaces
sender.Dispose();
}
catch (Exception)
{
sender.Dispose();
throw;
}
}
}
Expand Down

0 comments on commit 65e8e68

Please sign in to comment.