Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[System] Fix TCP socket reuse. #2047

Merged
merged 3 commits into from Sep 17, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
62 changes: 61 additions & 1 deletion mcs/class/System/Test/System.Net.Sockets/SocketTest.cs
Expand Up @@ -9,8 +9,10 @@
//

using System;
using System.Linq;
using System.Collections;
using System.Threading;
using System.Text.RegularExpressions;
using System.Net;
using System.Net.Sockets;
using NUnit.Framework;
Expand Down Expand Up @@ -3476,7 +3478,65 @@ public void UdpDoubleBind ()
ss.Close ();
s.Close ();
}


static bool supportsTcpReuse = false;
static bool supportsTcpReuseSet = false;

static bool SupportsTcpReuse ()
{
if (supportsTcpReuseSet)
return supportsTcpReuse;

if (Path.DirectorySeparatorChar == '/') {
/*
* On UNIX OS
* Multiple threads listening to the same address and port are not possible
* before linux 3.9 kernel, where the socket option SO_REUSEPORT was introduced.
*/
Regex reg = new Regex(@"^#define\s*SO_REUSEPORT");
foreach (string directory in Directory.GetDirectories ("/usr/include")) {
var f = Directory.GetFiles (directory, "socket.h").SingleOrDefault ();
if (f != null && File.ReadLines (f).Any (l => reg.Match (l).Success)) {
supportsTcpReuse = true;
break;
}
}
} else {
supportsTcpReuse = true;
}

supportsTcpReuseSet = true;

return supportsTcpReuse;
}

// Test case for bug #31557
[Test]
public void TcpDoubleBind ()
{
using (Socket s = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp))
using (Socket ss = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp)) {
s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

s.Bind (new IPEndPoint (IPAddress.Any, 12345));
s.Listen(1);

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

Exception ex = null;
try {
ss.Bind (new IPEndPoint (IPAddress.Any, 12345));
ss.Listen(1);
} catch (SocketException e) {
ex = e;
}

Assert.AreEqual (SupportsTcpReuse (), ex == null);
}
}

[Test]
[Category ("NotOnMac")]
public void ConnectedProperty ()
Expand Down
2 changes: 1 addition & 1 deletion mono/io-layer/sockets.c
Expand Up @@ -733,7 +733,7 @@ int _wapi_setsockopt(guint32 fd, int level, int optname,
socklen_t type_len = sizeof (type);

if (!getsockopt (fd, level, SO_TYPE, &type, &type_len)) {
if (type == SOCK_DGRAM)
if (type == SOCK_DGRAM || type == SOCK_STREAM)
setsockopt (fd, level, SO_REUSEPORT, tmp_val, optlen);
}
}
Expand Down