Skip to content

Commit

Permalink
fix: fixing udp socket exception on linux (#809)
Browse files Browse the repository at this point in the history
wrapping IOControl in try/catch, only setting it on windows
  • Loading branch information
James-Frowen committed May 24, 2021
1 parent 4d0f092 commit a4e8689
Showing 1 changed file with 32 additions and 16 deletions.
48 changes: 32 additions & 16 deletions Assets/Mirage/Runtime/Sockets/Udp/UdpSocketFactory.cs
Expand Up @@ -72,10 +72,6 @@ public class UdpSocket : ISocket
Socket socket;
IPEndPoint AnyEndpoint;

public UdpSocket()
{
}

public void Bind(EndPoint endPoint)
{
AnyEndpoint = endPoint as IPEndPoint;
Expand All @@ -94,22 +90,42 @@ static Socket CreateSocket(EndPoint endPoint)
};

socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

// stops "SocketException: Connection reset by peer"
// this error seems to be caused by a failed send, resulting in the next polling being true, even those endpoint is closed
// see https://stackoverflow.com/a/15232187/8479976

// this IOControl sets the reporting of "unrealable" to false, stoping SocketException after a connection closes without sending disconnect message
const uint IOC_IN = 0x80000000;
const uint IOC_VENDOR = 0x18000000;
const uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
byte[] _false = new byte[] { 0, 0, 0, 0 };

socket.IOControl(unchecked((int)SIO_UDP_CONNRESET), _false, null);
TrySetIOControl(socket);

return socket;
}

private static void TrySetIOControl(Socket socket)
{
try
{
if (Application.platform != RuntimePlatform.WindowsPlayer && Application.platform != RuntimePlatform.WindowsEditor)
{
// IOControl only seems to work on windows
// gives "SocketException: The descriptor is not a socket" when running on github action on Linux
// see https://github.com/mono/mono/blob/f74eed4b09790a0929889ad7fc2cf96c9b6e3757/mcs/class/System/System.Net.Sockets/Socket.cs#L2763-L2765
return;
}

// stops "SocketException: Connection reset by peer"
// this error seems to be caused by a failed send, resulting in the next polling being true, even those endpoint is closed
// see https://stackoverflow.com/a/15232187/8479976

// this IOControl sets the reporting of "unrealable" to false, stoping SocketException after a connection closes without sending disconnect message
const uint IOC_IN = 0x80000000;
const uint IOC_VENDOR = 0x18000000;
const uint SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;
byte[] _false = new byte[] { 0, 0, 0, 0 };

socket.IOControl(unchecked((int)SIO_UDP_CONNRESET), _false, null);
}
catch (Exception e)
{
Debug.LogError("Exception setting IOControl");
Debug.LogException(e);
}
}

public void Connect(EndPoint endPoint)
{
AnyEndpoint = endPoint as IPEndPoint;
Expand Down

0 comments on commit a4e8689

Please sign in to comment.