Skip to content

Commit

Permalink
Merge pull request #61 from rdavisau/fix-odd-udp-issue
Browse files Browse the repository at this point in the history
prevent exception if UdpClient receives an ICMP unreachable packet
  • Loading branch information
rdavisau committed Jan 10, 2016
2 parents 108df61 + 0bbfed8 commit 34f7b1b
Show file tree
Hide file tree
Showing 4 changed files with 17 additions and 2 deletions.
13 changes: 12 additions & 1 deletion Sockets/Sockets.Implementation.NET/UdpSocketBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,18 @@ protected Task SendToAsync(byte[] data, int length, string address, int port)
.SendAsync(data, length, address, port)
.WrapNativeSocketExceptions();
}


protected void ProtectAgainstICMPUnreachable(UdpClient udpClient)
{
// this should be called whenever the backing client is recreated.
// it prevents a strange class of errors, some discussion at
// http://stackoverflow.com/questions/7201862/an-existing-connection-was-forcibly-closed-by-the-remote-host

uint IOC_IN = 0x80000000;
uint IOC_VENDOR = 0x18000000;
uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
udpClient.Client.IOControl((int)SIO_UDP_CONNRESET, new[] { Convert.ToByte(false) }, null);
}

/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
Expand Down
3 changes: 2 additions & 1 deletion Sockets/Sockets.Implementation.NET/UdpSocketClient.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System;
using System.Net.Sockets;
using System.Threading;
using System.Threading.Tasks;
Expand Down Expand Up @@ -30,8 +31,8 @@ public UdpSocketClient()
_backingUdpClient = new UdpClient
{
EnableBroadcast = true

};
ProtectAgainstICMPUnreachable(_backingUdpClient);
}
catch (PlatformSocketException ex)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ public async Task JoinMulticastGroupAsync(string multicastAddress, int port, ICo
{
EnableBroadcast = true
};
ProtectAgainstICMPUnreachable(_backingUdpClient);
}
catch (PlatformSocketException ex)
{
Expand Down
2 changes: 2 additions & 0 deletions Sockets/Sockets.Implementation.NET/UdpSocketReceiver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ public Task StartListeningAsync(int port = 0, ICommsInterface listenOn = null)
{
EnableBroadcast = true
};
ProtectAgainstICMPUnreachable(_backingUdpClient);
RunMessageReceiver(_messageCanceller.Token);
})
Expand Down Expand Up @@ -91,6 +92,7 @@ public Task StopListeningAsync()
try
{
_backingUdpClient = new UdpClient { EnableBroadcast = true };
ProtectAgainstICMPUnreachable(_backingUdpClient);
}
catch (PlatformSocketException ex)
{
Expand Down

0 comments on commit 34f7b1b

Please sign in to comment.