Imported Upstream version 5.10.0.69

Former-commit-id: fc39669a0b707dd3c063977486506b6793da2890
This commit is contained in:
Xamarin Public Jenkins (auto-signing)
2018-01-29 19:03:06 +00:00
parent d8f8abd549
commit e2950ec768
6283 changed files with 453847 additions and 91879 deletions

View File

@@ -3,7 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Net.Test.Common;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
@@ -33,59 +33,64 @@ namespace System.Net.Sockets.Tests
[OuterLoop] // TODO: Issue #11345
[Fact]
public void ConnectWithV4_Success()
public async Task ConnectWithV4_Success()
{
int port;
TcpListener listener = SocketTestExtensions.CreateAndStartTcpListenerOnAnonymousPort(out port);
IAsyncResult asyncResult = listener.BeginAcceptTcpClient(null, null);
TcpListener listener = SocketTestExtensions.CreateAndStartTcpListenerOnAnonymousPort(out int port);
Task<TcpClient> acceptTask = Task.Factory.FromAsync(listener.BeginAcceptTcpClient(null, null), listener.EndAcceptTcpClient);
TcpClient client = new TcpClient(AddressFamily.InterNetwork);
client.ConnectAsync(IPAddress.Loopback, port).GetAwaiter().GetResult();
Task connectTask = client.ConnectAsync(IPAddress.Loopback, port);
TcpClient acceptedClient = listener.EndAcceptTcpClient(asyncResult);
await (new Task[] { acceptTask, connectTask }).WhenAllOrAnyFailed();
client.Dispose();
acceptedClient.Dispose();
acceptTask.Result.Dispose();
listener.Stop();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void ConnectWithV6_Success()
public async Task ConnectWithV6_Success()
{
int port;
TcpListener listener = SocketTestExtensions.CreateAndStartTcpListenerOnAnonymousPort(out port);
IAsyncResult asyncResult = listener.BeginAcceptTcpClient(null, null);
TcpListener listener = SocketTestExtensions.CreateAndStartTcpListenerOnAnonymousPort(out int port);
Task<TcpClient> acceptTask = Task.Factory.FromAsync(listener.BeginAcceptTcpClient(null, null), listener.EndAcceptTcpClient);
TcpClient client = new TcpClient(AddressFamily.InterNetworkV6);
client.ConnectAsync(IPAddress.IPv6Loopback, port).GetAwaiter().GetResult();
Task connectTask = client.ConnectAsync(IPAddress.IPv6Loopback, port);
await (new Task[] { acceptTask, connectTask }).WhenAllOrAnyFailed();
TcpClient acceptedClient = listener.EndAcceptTcpClient(asyncResult);
client.Dispose();
acceptedClient.Dispose();
acceptTask.Result.Dispose();
listener.Stop();
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void ConnectWithV4AndV6_Success()
public async Task ConnectWithV4AndV6_Success()
{
int port;
TcpListener listener = SocketTestExtensions.CreateAndStartTcpListenerOnAnonymousPort(out port);
IAsyncResult asyncResult = listener.BeginAcceptTcpClient(null, null);
TcpListener listener = SocketTestExtensions.CreateAndStartTcpListenerOnAnonymousPort(out int port);
Task<TcpClient> acceptTask = Task.Factory.FromAsync(listener.BeginAcceptTcpClient(null, null), listener.EndAcceptTcpClient);
TcpClient v6Client = new TcpClient(AddressFamily.InterNetworkV6);
v6Client.ConnectAsync(IPAddress.IPv6Loopback, port).GetAwaiter().GetResult();
Task connectTask = v6Client.ConnectAsync(IPAddress.IPv6Loopback, port);
TcpClient acceptedV6Client = listener.EndAcceptTcpClient(asyncResult);
Task[] tasks = new Task[] { acceptTask, connectTask };
await tasks.WhenAllOrAnyFailed();
TcpClient acceptedV6Client = acceptTask.Result;
Assert.Equal(AddressFamily.InterNetworkV6, acceptedV6Client.Client.RemoteEndPoint.AddressFamily);
Assert.Equal(AddressFamily.InterNetworkV6, v6Client.Client.RemoteEndPoint.AddressFamily);
asyncResult = listener.BeginAcceptTcpClient(null, null);
acceptTask = Task.Factory.FromAsync(listener.BeginAcceptTcpClient(null, null), listener.EndAcceptTcpClient);
TcpClient v4Client = new TcpClient(AddressFamily.InterNetwork);
v4Client.ConnectAsync(IPAddress.Loopback, port).GetAwaiter().GetResult();
connectTask = v4Client.ConnectAsync(IPAddress.Loopback, port);
tasks[0] = acceptTask;
tasks[1] = connectTask;
await tasks.WhenAllOrAnyFailed();
TcpClient acceptedV4Client = listener.EndAcceptTcpClient(asyncResult);
TcpClient acceptedV4Client = acceptTask.Result;
Assert.Equal(AddressFamily.InterNetworkV6, acceptedV4Client.Client.RemoteEndPoint.AddressFamily);
Assert.Equal(AddressFamily.InterNetwork, v4Client.Client.RemoteEndPoint.AddressFamily);

View File

@@ -12,7 +12,7 @@ namespace System.Net.Sockets.Tests
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public void Connect_Success(IPAddress listenAt)
public async Task Connect_Success(IPAddress listenAt)
{
int port;
using (SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, listenAt, out port))
@@ -20,7 +20,7 @@ namespace System.Net.Sockets.Tests
using (Socket client = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
Task connectTask = ConnectAsync(client, new IPEndPoint(listenAt, port));
Assert.True(connectTask.Wait(TestSettings.PassingTestTimeout), "IPv4: Timed out while waiting for connection");
await connectTask;
Assert.True(client.Connected);
}
}
@@ -29,7 +29,7 @@ namespace System.Net.Sockets.Tests
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public void Connect_MultipleIPAddresses_Success(IPAddress listenAt)
public async Task Connect_MultipleIPAddresses_Success(IPAddress listenAt)
{
if (!SupportsMultiConnect)
return;
@@ -39,7 +39,7 @@ namespace System.Net.Sockets.Tests
using (Socket client = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
Task connectTask = MultiConnectAsync(client, new IPAddress[] { IPAddress.Loopback, IPAddress.IPv6Loopback }, port);
Assert.True(connectTask.Wait(TestSettings.PassingTestTimeout), "Timed out while waiting for connection");
await connectTask;
Assert.True(client.Connected);
}
}

View File

@@ -69,6 +69,8 @@ namespace System.Net.Sockets.Tests
client.Disconnect(reuseSocket);
Assert.False(client.Connected);
args.RemoteEndPoint = server2.EndPoint;
if (client.ConnectAsync(args))
@@ -114,6 +116,7 @@ namespace System.Net.Sockets.Tests
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.False(client.Connected);
args.RemoteEndPoint = server2.EndPoint;
@@ -155,6 +158,9 @@ namespace System.Net.Sockets.Tests
IAsyncResult ar = client.BeginDisconnect(reuseSocket, null, null);
client.EndDisconnect(ar);
Assert.False(client.Connected);
Assert.Throws<InvalidOperationException>(() => client.EndDisconnect(ar));
args.RemoteEndPoint = server2.EndPoint;

View File

@@ -1 +1 @@
fba1acd2981dbca4cd81d47d3c20272000a172bb
7d137cf0130b6828c9a7055b901946bea8df703a

View File

@@ -3,6 +3,7 @@
// See the LICENSE file in the project root for more information.
using System.Threading;
using Xunit;
namespace System.Net.Sockets.Tests
@@ -42,20 +43,121 @@ namespace System.Net.Sockets.Tests
}
}
[PlatformSpecific(TestPlatforms.Windows)] // Windows IOCTL
[Fact]
public void IOControl_FIONREAD_Success()
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
byte[] outValue = new byte[sizeof(int)];
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.DataToRead, null, null));
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.DataToRead, null, new byte[0]));
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.DataToRead, null, new byte[sizeof(int) - 1]));
const int FIONREAD = 0x4004667F;
Assert.Equal(4, client.IOControl(FIONREAD, null, outValue));
Assert.Equal(client.Available, BitConverter.ToInt32(outValue, 0));
byte[] fionreadResult = new byte[sizeof(int)];
Assert.Equal(4, client.IOControl(IOControlCode.DataToRead, null, outValue));
Assert.Equal(client.Available, BitConverter.ToInt32(outValue, 0));
Assert.Equal(4, client.IOControl(IOControlCode.DataToRead, null, fionreadResult));
Assert.Equal(client.Available, BitConverter.ToInt32(fionreadResult, 0));
Assert.Equal(0, BitConverter.ToInt32(fionreadResult, 0));
Assert.Equal(4, client.IOControl((int)IOControlCode.DataToRead, null, fionreadResult));
Assert.Equal(client.Available, BitConverter.ToInt32(fionreadResult, 0));
Assert.Equal(0, BitConverter.ToInt32(fionreadResult, 0));
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
client.Connect(listener.LocalEndPoint);
using (Socket server = listener.Accept())
{
server.Send(new byte[] { 42 });
Assert.True(SpinWait.SpinUntil(() => client.Available != 0, 10_000));
Assert.Equal(4, client.IOControl(IOControlCode.DataToRead, null, fionreadResult));
Assert.Equal(client.Available, BitConverter.ToInt32(fionreadResult, 0));
Assert.Equal(1, BitConverter.ToInt32(fionreadResult, 0));
}
}
}
}
[ActiveIssue(25639)]
[Fact]
public void IOControl_SIOCATMARK_Success()
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.OobDataRead, null, null));
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.OobDataRead, null, new byte[0]));
Assert.Throws<SocketException>(() => client.IOControl(IOControlCode.OobDataRead, null, new byte[sizeof(int) - 1]));
using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
client.Connect(listener.LocalEndPoint);
using (Socket server = listener.Accept())
{
byte[] siocatmarkResult = new byte[sizeof(int)];
server.Send(new byte[] { 42 }, SocketFlags.None);
server.Send(new byte[] { 43 }, SocketFlags.OutOfBand);
Assert.Equal(4, client.IOControl(IOControlCode.OobDataRead, null, siocatmarkResult));
Assert.Equal(0, BitConverter.ToInt32(siocatmarkResult, 0));
var received = new byte[1];
Assert.Equal(1, client.Receive(received));
Assert.Equal(42, received[0]);
Assert.Equal(1, client.Receive(received, SocketFlags.OutOfBand));
Assert.Equal(43, received[0]);
Assert.True(SpinWait.SpinUntil(() =>
{
Assert.Equal(4, client.IOControl(IOControlCode.OobDataRead, null, siocatmarkResult));
return BitConverter.ToInt32(siocatmarkResult, 0) == 1;
}, 10_000));
}
}
}
}
[Fact]
public void IOControl_FIONBIO_Throws()
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Assert.Throws<InvalidOperationException>(() => client.IOControl(unchecked((int)IOControlCode.NonBlockingIO), null, null));
Assert.Throws<InvalidOperationException>(() => client.IOControl(IOControlCode.NonBlockingIO, null, null));
}
}
[PlatformSpecific(TestPlatforms.AnyUnix)]
[Fact]
public void IOControl_UnknownValues_Unix_Throws()
{
using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
foreach (IOControlCode code in Enum.GetValues(typeof(IOControlCode)))
{
switch (code)
{
case IOControlCode.NonBlockingIO:
case IOControlCode.DataToRead:
case IOControlCode.OobDataRead:
// These three codes are currently enabled on Unix.
break;
default:
// The rest should throw PNSE.
Assert.Throws<PlatformNotSupportedException>(() => client.IOControl((int)code, null, null));
Assert.Throws<PlatformNotSupportedException>(() => client.IOControl(code, null, null));
break;
}
}
}
}
}

View File

@@ -146,7 +146,7 @@ namespace System.Net.Sockets.Tests
}
[PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/308
[Fact]
public void Select_Error_OneReadyAtATime()
{
const int Errors = 90; // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation
@@ -241,7 +241,7 @@ namespace System.Net.Sockets.Tests
[OuterLoop]
[Fact]
public static void Select_AcceptNonBlocking_Success()
public static async Task Select_AcceptNonBlocking_Success()
{
using (Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
@@ -264,8 +264,7 @@ namespace System.Net.Sockets.Tests
}
// Give the task 5 seconds to complete; if not, assume it's hung.
bool completed = t.Wait(5000);
Assert.True(completed);
await t.TimeoutAfter(5000);
}
}

View File

@@ -141,7 +141,7 @@ namespace System.Net.Sockets.Tests
using (remote)
{
var recvBuffer = new byte[256];
for (;;)
for (; ; )
{
int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None);
if (received == 0)
@@ -183,7 +183,7 @@ namespace System.Net.Sockets.Tests
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(SendFile_MemberData))]
public void SendFile_APM(IPAddress listenAt, bool sendPreAndPostBuffers, int bytesToSend)
public async Task SendFile_APM(IPAddress listenAt, bool sendPreAndPostBuffers, int bytesToSend)
{
const int ListenBacklog = 1, TestTimeout = 30000;
@@ -228,10 +228,7 @@ namespace System.Net.Sockets.Tests
});
// Wait for the tasks to complete
Task<Task> firstCompleted = Task.WhenAny(serverTask, clientTask);
Assert.True(firstCompleted.Wait(TestTimeout), "Neither client nor server task completed within allowed time");
firstCompleted.Result.GetAwaiter().GetResult();
Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout), $"Tasks didn't complete within allowed time. Server:{serverTask.Status} Client:{clientTask.Status}");
await (new[] { serverTask, clientTask }).WhenAllOrAnyFailed(TestTimeout);
// Validate the results
Assert.Equal(bytesToSend, bytesReceived);

View File

@@ -19,7 +19,7 @@ namespace System.Net.Sockets.Tests
[InlineData(1, 1, 2)] // count high
public async Task InvalidArguments_Throws(int? length, int offset, int count)
{
if (length == null && !ValidatesArrayArguments) return;
if (!ValidatesArrayArguments) return;
using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
@@ -137,7 +137,7 @@ namespace System.Net.Sockets.Tests
if (!useMultipleBuffers)
{
var recvBuffer = new byte[256];
for (;;)
for (; ; )
{
int received = await ReceiveAsync(remote, new ArraySegment<byte>(recvBuffer));
if (received == 0)
@@ -156,7 +156,7 @@ namespace System.Net.Sockets.Tests
new ArraySegment<byte>(new byte[256], 2, 100),
new ArraySegment<byte>(new byte[1], 0, 0),
new ArraySegment<byte>(new byte[64], 9, 33)};
for (;;)
for (; ; )
{
int received = await ReceiveAsync(remote, recvBuffers);
if (received == 0)
@@ -553,7 +553,7 @@ namespace System.Net.Sockets.Tests
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(LoopbacksAndBuffers))]
public void SendRecvPollSync_TcpListener_Socket(IPAddress listenAt, bool pollBeforeOperation)
public async Task SendRecvPollSync_TcpListener_Socket(IPAddress listenAt, bool pollBeforeOperation)
{
const int BytesToSend = 123456;
const int ListenBacklog = 1;
@@ -619,10 +619,12 @@ namespace System.Net.Sockets.Tests
bytesSent += sent;
sentChecksum.Add(sendBuffer, 0, sent);
}
client.Shutdown(SocketShutdown.Send);
}
});
Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout), "Wait timed out");
await (new[] { serverTask, clientTask }).WhenAllOrAnyFailed(TestTimeout);
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);
@@ -697,6 +699,7 @@ namespace System.Net.Sockets.Tests
Assert.False(receive.IsCompleted, $"Task should not have been completed, was {receive.Status}");
// Disconnect the client
server.Shutdown(SocketShutdown.Both);
server.Close();
// The client should now wake up
@@ -868,6 +871,8 @@ namespace System.Net.Sockets.Tests
Assert.Equal(SegmentCount, bytesSent);
Assert.Equal(SocketError.Success, error);
acceptSocket.Shutdown(SocketShutdown.Send);
}
});
@@ -1041,7 +1046,7 @@ namespace System.Net.Sockets.Tests
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public void SendToRecvFromAsync_Datagram_UDP_UdpClient(IPAddress loopbackAddress)
public async Task SendToRecvFromAsync_Datagram_UDP_UdpClient(IPAddress loopbackAddress)
{
IPAddress leftAddress = loopbackAddress, rightAddress = loopbackAddress;
@@ -1107,7 +1112,7 @@ namespace System.Net.Sockets.Tests
}
});
Assert.True(Task.WaitAll(new[] { receiverTask, senderTask }, TestTimeout));
await (new[] { receiverTask, senderTask }).WhenAllOrAnyFailed(TestTimeout);
for (int i = 0; i < DatagramsToSend; i++)
{
Assert.NotNull(receivedChecksums[i]);
@@ -1122,7 +1127,7 @@ namespace System.Net.Sockets.Tests
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(Loopbacks))]
public void SendRecvAsync_TcpListener_TcpClient(IPAddress listenAt)
public async Task SendRecvAsync_TcpListener_TcpClient(IPAddress listenAt)
{
const int BytesToSend = 123456;
const int ListenBacklog = 1;
@@ -1140,7 +1145,7 @@ namespace System.Net.Sockets.Tests
using (NetworkStream stream = remote.GetStream())
{
var recvBuffer = new byte[256];
for (;;)
for (; ; )
{
int received = await stream.ReadAsync(recvBuffer, 0, recvBuffer.Length);
if (received == 0)
@@ -1184,8 +1189,7 @@ namespace System.Net.Sockets.Tests
}
});
Assert.True(Task.WaitAll(new[] { serverTask, clientTask }, TestTimeout),
$"Time out waiting for serverTask ({serverTask.Status}) and clientTask ({clientTask.Status})");
await (new[] { serverTask, clientTask }).WhenAllOrAnyFailed(TestTimeout);
Assert.Equal(bytesSent, bytesReceived);
Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum);

View File

@@ -7,4 +7,5 @@ namespace System.Net.Sockets.Tests
public sealed class SendReceiveSpanSync : SendReceive<SocketHelperSpanSync> { }
public sealed class SendReceiveSpanSyncForceNonBlocking : SendReceive<SocketHelperSpanSyncForceNonBlocking> { }
public sealed class SendReceiveMemoryArrayTask : SendReceive<SocketHelperMemoryArrayTask> { }
public sealed class SendReceiveMemoryNativeTask : SendReceive<SocketHelperMemoryNativeTask> { }
}

View File

@@ -10,7 +10,7 @@ using Xunit;
namespace System.Net.Sockets.Tests
{
public class SocketAsyncEventArgsTest
public partial class SocketAsyncEventArgsTest
{
[Fact]
public void Usertoken_Roundtrips()
@@ -154,6 +154,12 @@ namespace System.Net.Sockets.Tests
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 0, 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(new byte[1], 1, 2));
saea.SetBuffer(new byte[2], 0, 2);
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => saea.SetBuffer(-1, 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("offset", () => saea.SetBuffer(3, 2));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => saea.SetBuffer(0, 3));
}
}
@@ -327,7 +333,8 @@ namespace System.Net.Sockets.Tests
connectSaea.Completed += (s, e) => tcs.SetResult(e.SocketError);
connectSaea.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listen.LocalEndPoint).Port);
Assert.True(client.ConnectAsync(connectSaea), $"ConnectAsync completed synchronously with SocketError == {connectSaea.SocketError}");
bool pending = client.ConnectAsync(connectSaea);
if (!pending) tcs.SetResult(connectSaea.SocketError);
if (tcs.Task.IsCompleted)
{
Assert.NotEqual(SocketError.Success, tcs.Task.Result);

View File

@@ -0,0 +1,195 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Collections.Generic;
using Xunit;
namespace System.Net.Sockets.Tests
{
public partial class SocketAsyncEventArgsTest
{
[Fact]
public void SetBuffer_MemoryBuffer_Roundtrips()
{
using (var saea = new SocketAsyncEventArgs())
{
Memory<byte> memory = new byte[42];
saea.SetBuffer(memory);
Assert.True(memory.Equals(saea.MemoryBuffer));
Assert.Equal(0, saea.Offset);
Assert.Equal(memory.Length, saea.Count);
Assert.Null(saea.Buffer);
}
}
[Fact]
public void SetBufferMemory_ThenSetBufferIntInt_Throws()
{
using (var saea = new SocketAsyncEventArgs())
{
Memory<byte> memory = new byte[42];
saea.SetBuffer(memory);
Assert.Throws<InvalidOperationException>(() => saea.SetBuffer(0, 42));
Assert.Throws<InvalidOperationException>(() => saea.SetBuffer(0, 0));
Assert.Throws<InvalidOperationException>(() => saea.SetBuffer(1, 2));
Assert.True(memory.Equals(saea.MemoryBuffer));
Assert.Equal(0, saea.Offset);
Assert.Equal(memory.Length, saea.Count);
}
}
[Fact]
public void SetBufferArrayIntInt_AvailableFromMemoryBuffer()
{
using (var saea = new SocketAsyncEventArgs())
{
byte[] array = new byte[42];
saea.SetBuffer(array, 0, array.Length);
Assert.True(saea.MemoryBuffer.TryGetArray(out ArraySegment<byte> result));
Assert.Same(array, result.Array);
Assert.Same(saea.Buffer, array);
Assert.Equal(0, result.Offset);
Assert.Equal(array.Length, result.Count);
saea.SetBuffer(1, 2);
Assert.Same(saea.Buffer, array);
Assert.Equal(1, saea.Offset);
Assert.Equal(2, saea.Count);
Assert.True(saea.MemoryBuffer.TryGetArray(out result));
Assert.Same(array, result.Array);
Assert.Equal(0, result.Offset);
Assert.Equal(array.Length, result.Count);
}
}
[Fact]
public void SetBufferMemory_Default_ResetsCountOffset()
{
using (var saea = new SocketAsyncEventArgs())
{
saea.SetBuffer(42, 84);
Assert.Equal(0, saea.Offset);
Assert.Equal(0, saea.Count);
saea.SetBuffer(new byte[3], 1, 2);
Assert.Equal(1, saea.Offset);
Assert.Equal(2, saea.Count);
saea.SetBuffer(Memory<byte>.Empty);
Assert.Null(saea.Buffer);
Assert.Equal(0, saea.Offset);
Assert.Equal(0, saea.Count);
}
}
[Fact]
public void SetBufferListWhenMemoryBufferSet_Throws()
{
using (var saea = new SocketAsyncEventArgs())
{
var bufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) };
Memory<byte> buffer = new byte[1];
saea.SetBuffer(buffer);
AssertExtensions.Throws<ArgumentException>(null, () => saea.BufferList = bufferList);
Assert.True(buffer.Equals(saea.MemoryBuffer));
Assert.Equal(0, saea.Offset);
Assert.Equal(buffer.Length, saea.Count);
Assert.Null(saea.BufferList);
saea.SetBuffer(Memory<byte>.Empty);
saea.BufferList = bufferList; // works fine when Buffer has been set back to null
}
}
[Fact]
public void SetBufferMemoryWhenBufferListSet_Throws()
{
using (var saea = new SocketAsyncEventArgs())
{
var bufferList = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[1]) };
saea.BufferList = bufferList;
saea.SetBuffer(Memory<byte>.Empty); // nop
Memory<byte> buffer = new byte[2];
AssertExtensions.Throws<ArgumentException>(null, () => saea.SetBuffer(buffer));
Assert.Same(bufferList, saea.BufferList);
Assert.Null(saea.Buffer);
Assert.True(saea.MemoryBuffer.Equals(default));
saea.BufferList = null;
saea.SetBuffer(buffer); // works fine when BufferList has been set back to null
}
}
[Fact]
public void SetBufferMemoryWhenBufferMemorySet_Succeeds()
{
using (var saea = new SocketAsyncEventArgs())
{
Memory<byte> buffer1 = new byte[1];
Memory<byte> buffer2 = new byte[2];
for (int i = 0; i < 2; i++)
{
saea.SetBuffer(buffer1);
Assert.Null(saea.Buffer);
Assert.True(saea.MemoryBuffer.Equals(buffer1));
Assert.Equal(0, saea.Offset);
Assert.Equal(buffer1.Length, saea.Count);
}
saea.SetBuffer(buffer2);
Assert.Null(saea.Buffer);
Assert.True(saea.MemoryBuffer.Equals(buffer2));
Assert.Equal(0, saea.Offset);
Assert.Equal(buffer2.Length, saea.Count);
}
}
[Fact]
public void SetBufferMemoryWhenBufferSet_Succeeds()
{
using (var saea = new SocketAsyncEventArgs())
{
byte[] buffer1 = new byte[3];
Memory<byte> buffer2 = new byte[4];
saea.SetBuffer(buffer1, 0, buffer1.Length);
Assert.Same(buffer1, saea.Buffer);
Assert.Equal(0, saea.Offset);
Assert.Equal(buffer1.Length, saea.Count);
saea.SetBuffer(1, 2);
Assert.Same(buffer1, saea.Buffer);
Assert.Equal(1, saea.Offset);
Assert.Equal(2, saea.Count);
saea.SetBuffer(buffer2);
Assert.Null(saea.Buffer);
Assert.True(saea.MemoryBuffer.Equals(buffer2));
Assert.Equal(0, saea.Offset);
Assert.Equal(buffer2.Length, saea.Count);
}
}
[Fact]
public void SetBufferMemory_NonArray_BufferReturnsNull()
{
using (var m = new NativeOwnedMemory(42))
using (var saea = new SocketAsyncEventArgs())
{
saea.SetBuffer(m.Memory);
Assert.True(saea.MemoryBuffer.Equals(m.Memory));
Assert.Equal(0, saea.Offset);
Assert.Equal(m.Length, saea.Count);
Assert.Null(saea.Buffer);
}
}
}
}

View File

@@ -87,11 +87,6 @@ namespace System.Net.Sockets.Tests
[Fact]
public async Task MulticastInterface_Set_AnyInterface_Succeeds()
{
if (PlatformDetection.IsFedora)
{
return; // [ActiveIssue(24008)]
}
// On all platforms, index 0 means "any interface"
await MulticastInterface_Set_Helper(0);
}
@@ -122,11 +117,7 @@ namespace System.Net.Sockets.Tests
receiveSocket.ReceiveTimeout = 1000;
receiveSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(multicastAddress, interfaceIndex));
// https://github.com/Microsoft/BashOnWindows/issues/990
if (!PlatformDetection.IsWindowsSubsystemForLinux)
{
sendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex));
}
sendSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(interfaceIndex));
var receiveBuffer = new byte[1024];
var receiveTask = receiveSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), SocketFlags.None);
@@ -159,6 +150,81 @@ namespace System.Net.Sockets.Tests
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task MulticastInterface_Set_IPv6_AnyInterface_Succeeds()
{
if (PlatformDetection.IsFedora || PlatformDetection.IsRedHatFamily7 || PlatformDetection.IsOSX)
{
return; // [ActiveIssue(24008)]
}
// On all platforms, index 0 means "any interface"
await MulticastInterface_Set_IPv6_Helper(0);
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[ActiveIssue(21327, TargetFrameworkMonikers.Uap)] // UWP Apps are forbidden to send network traffic to the local Computer.
public async void MulticastInterface_Set_IPv6_Loopback_Succeeds()
{
// On Windows, we can apparently assume interface 1 is "loopback." On other platforms, this is not a
// valid assumption. We could maybe use NetworkInterface.LoopbackInterfaceIndex to get the index, but
// this would introduce a dependency on System.Net.NetworkInformation, which depends on System.Net.Sockets,
// which is what we're testing here.... So for now, we'll just assume "loopback == 1" and run this on
// Windows only.
await MulticastInterface_Set_IPv6_Helper(1);
}
private async Task MulticastInterface_Set_IPv6_Helper(int interfaceIndex)
{
IPAddress multicastAddress = IPAddress.Parse("ff11::1:1");
string message = "hello";
int port;
using (Socket receiveSocket = CreateBoundUdpIPv6Socket(out port),
sendSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp))
{
receiveSocket.ReceiveTimeout = 1000;
receiveSocket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption(multicastAddress, interfaceIndex));
// https://github.com/Microsoft/BashOnWindows/issues/990
if (!PlatformDetection.IsWindowsSubsystemForLinux)
{
sendSocket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastInterface, interfaceIndex);
}
var receiveBuffer = new byte[1024];
var receiveTask = receiveSocket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), SocketFlags.None);
for (int i = 0; i < TestSettings.UDPRedundancy; i++)
{
sendSocket.SendTo(Encoding.UTF8.GetBytes(message), new IPEndPoint(multicastAddress, port));
}
var cts = new CancellationTokenSource();
Assert.True(await Task.WhenAny(receiveTask, Task.Delay(20_000, cts.Token)) == receiveTask, "Waiting for received data timed out");
cts.Cancel();
int bytesReceived = await receiveTask;
string receivedMessage = Encoding.UTF8.GetString(receiveBuffer, 0, bytesReceived);
Assert.Equal(receivedMessage, message);
}
}
[Fact]
public void MulticastInterface_Set_IPv6_InvalidIndex_Throws()
{
int interfaceIndex = 31415;
using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp))
{
Assert.Throws<SocketException>(() =>
s.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastInterface, interfaceIndex));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // In WSL, the connect() call fails immediately.
[InlineData(false)]
@@ -224,6 +290,21 @@ namespace System.Net.Sockets.Tests
return receiveSocket;
}
// Create an Udp Socket and binds it to an available port
private static Socket CreateBoundUdpIPv6Socket(out int localPort)
{
Socket receiveSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
// sending a message will bind the socket to an available port
string sendMessage = "dummy message";
int port = 54320;
IPAddress multicastAddress = IPAddress.Parse("ff11::1:1");
receiveSocket.SendTo(Encoding.UTF8.GetBytes(sendMessage), new IPEndPoint(multicastAddress, port));
localPort = (receiveSocket.LocalEndPoint as IPEndPoint).Port;
return receiveSocket;
}
[Theory]
[InlineData(null, null, null, true)]
[InlineData(null, null, false, true)]
@@ -284,6 +365,88 @@ namespace System.Net.Sockets.Tests
ReuseAddress(exclusiveAddressUse, firstSocketReuseAddress, secondSocketReuseAddress, expectFailure);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Windows defaults are different
public void ExclusiveAddress_Default_Unix()
{
using (Socket a = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
Assert.Equal(1, (int)a.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse));
Assert.Equal(true, a.ExclusiveAddressUse);
Assert.Equal(0, (int)a.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress));
}
}
[Theory]
[InlineData(1)]
[InlineData(0)]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix does not have separate options for ExclusiveAddressUse and ReuseAddress.
public void SettingExclusiveAddress_SetsReuseAddress(int value)
{
using (Socket a = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
a.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, value);
Assert.Equal(value, (int)a.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse));
Assert.Equal(value == 1 ? 0 : 1, (int)a.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress));
}
// SettingReuseAddress_SetsExclusiveAddress
using (Socket a = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
{
a.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, value);
Assert.Equal(value, (int)a.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress));
Assert.Equal(value == 1 ? 0 : 1, (int)a.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse));
}
}
[Fact]
public void BindDuringTcpWait_Succeeds()
{
int port = 0;
using (Socket a = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
a.Bind(new IPEndPoint(IPAddress.Loopback, 0));
port = (a.LocalEndPoint as IPEndPoint).Port;
a.Listen(10);
// Connect a client
using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
client.Connect(new IPEndPoint(IPAddress.Loopback, port));
// accept socket and close it with zero linger time.
a.Accept().Close(0);
}
}
// Bind a socket to the same address we just used.
using (Socket b = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
b.Bind(new IPEndPoint(IPAddress.Loopback, port));
}
}
[Fact]
public void ExclusiveAddressUseTcp()
{
using (Socket a = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
// ExclusiveAddressUse defaults to true on Unix, on Windows it defaults to false.
a.ExclusiveAddressUse = true;
a.Bind(new IPEndPoint(IPAddress.Loopback, 0));
a.Listen(10);
int port = (a.LocalEndPoint as IPEndPoint).Port;
using (Socket b = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
SocketException ex = Assert.ThrowsAny<SocketException>(() => b.Bind(new IPEndPoint(IPAddress.Loopback, port)));
Assert.Equal(SocketError.AddressAlreadyInUse, ex.SocketErrorCode);
}
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[PlatformSpecific(TestPlatforms.Windows)] // SetIPProtectionLevel not supported on Unix

View File

@@ -2,12 +2,14 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Threading.Tasks;
namespace System.Net.Sockets.Tests
{
public class SocketHelperSpanSync : SocketHelperArraySync
{
public override bool ValidatesArrayArguments => false;
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
Task.Run(() => s.Receive((Span<byte>)buffer, SocketFlags.None));
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
@@ -16,6 +18,7 @@ namespace System.Net.Sockets.Tests
public sealed class SocketHelperSpanSyncForceNonBlocking : SocketHelperSpanSync
{
public override bool ValidatesArrayArguments => false;
public override Task<Socket> AcceptAsync(Socket s) =>
Task.Run(() => { s.ForceNonBlocking(true); Socket accepted = s.Accept(); accepted.ForceNonBlocking(true); return accepted; });
public override Task ConnectAsync(Socket s, EndPoint endPoint) =>
@@ -24,9 +27,32 @@ namespace System.Net.Sockets.Tests
public sealed class SocketHelperMemoryArrayTask : SocketHelperTask
{
public override bool ValidatesArrayArguments => false;
public override Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer) =>
s.ReceiveAsync((Memory<byte>)buffer, SocketFlags.None).AsTask();
public override Task<int> SendAsync(Socket s, ArraySegment<byte> buffer) =>
s.SendAsync((ReadOnlyMemory<byte>)buffer, SocketFlags.None).AsTask();
}
public sealed class SocketHelperMemoryNativeTask : SocketHelperTask
{
public override bool ValidatesArrayArguments => false;
public override async Task<int> ReceiveAsync(Socket s, ArraySegment<byte> buffer)
{
using (var m = new NativeOwnedMemory(buffer.Count))
{
int bytesReceived = await s.ReceiveAsync(m.Memory, SocketFlags.None).ConfigureAwait(false);
m.Memory.Span.Slice(0, bytesReceived).CopyTo(buffer.AsSpan());
return bytesReceived;
}
}
public override async Task<int> SendAsync(Socket s, ArraySegment<byte> buffer)
{
using (var m = new NativeOwnedMemory(buffer.Count))
{
buffer.AsSpan().CopyTo(m.Memory.Span);
return await s.SendAsync(m.Memory, SocketFlags.None).ConfigureAwait(false);
}
}
}
}

View File

@@ -3,6 +3,7 @@
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.props))\dir.props" />
<PropertyGroup>
<ProjectGuid>{8CBA022C-635F-4C8D-9D29-CD8AAC68C8E6}</ProjectGuid>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netstandard-Debug|AnyCPU'" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='netstandard-Release|AnyCPU'" />
@@ -43,10 +44,12 @@
<Compile Include="TcpClientTest.cs" />
<Compile Include="Shutdown.cs" />
<Compile Include="SocketAsyncEventArgsTest.cs" />
<Compile Include="SocketAsyncEventArgsTest.netcoreapp.cs" Condition="'$(TargetGroup)' != 'netstandard'" />
<Compile Include="SocketOptionNameTest.cs" />
<Compile Include="MulticastOptionTest.cs" />
<Compile Include="UdpClientTest.cs" />
<Compile Include="UnixDomainSocketTest.cs" />
<Compile Include="UnixDomainSocketTest.netcoreapp.cs" Condition="'$(TargetGroup)' != 'netstandard'" />
<!-- Common Sockets files -->
<Compile Include="$(CommonTestPath)\System\Net\Configuration.cs">
<Link>SocketCommon\Configuration.cs</Link>
@@ -91,12 +94,21 @@
<Compile Include="$(CommonTestPath)\System\ShouldNotBeInvokedException.cs">
<Link>Common\System\ShouldNotBeInvokedException.cs</Link>
</Compile>
<Compile Include="$(CommonTestPath)\System\Threading\Tasks\TaskTimeoutExtensions.cs">
<Link>Common\System\Threading\Tasks\TaskTimeoutExtensions.cs</Link>
</Compile>
<Compile Include="$(CommonTestPath)\System\Buffers\NativeOwnedMemory.cs">
<Link>Common\System\Buffers\NativeOwnedMemory.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Threading\Tasks\TaskToApm.cs">
<Link>Common\System\Threading\Tasks\TaskToApm.cs</Link>
</Compile>
<Compile Include="$(CommonTestPath)\System\Diagnostics\Tracing\TestEventListener.cs">
<Link>Common\System\Diagnostics\Tracing\TestEventListener.cs</Link>
</Compile>
<Compile Include="$(CommonPath)\System\Net\Logging\NetEventSource.Common.cs">
<Link>Common\System\Net\Logging\NetEventSource.Common.cs</Link>
</Compile>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="$(CommonTestPath)\System\Diagnostics\RemoteExecutorConsoleApp\RemoteExecutorConsoleApp.csproj">
@@ -108,4 +120,4 @@
<EmbeddedResource Include="Resources\$(AssemblyName).rd.xml" />
</ItemGroup>
<Import Project="$([MSBuild]::GetDirectoryNameOfFileAbove($(MSBuildThisFileDirectory), dir.targets))\dir.targets" />
</Project>
</Project>

View File

@@ -272,7 +272,6 @@ namespace System.Net.Sockets.Tests
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // ExclusiveAddressUse=false only supported on Windows
public void Roundtrip_ExclusiveAddressUse_GetEqualsSet_False()
{
using (TcpClient client = new TcpClient())
@@ -282,20 +281,6 @@ namespace System.Net.Sockets.Tests
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // ExclusiveAddressUse=false only supported on Windows
public void ExclusiveAddressUse_Set_False_NotSupported()
{
using (TcpClient client = new TcpClient())
{
Assert.Throws<SocketException>(() =>
{
client.ExclusiveAddressUse = false;
});
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void Roundtrip_LingerOption_GetEqualsSet()

View File

@@ -82,7 +82,8 @@ namespace System.Net.Sockets.Tests
Assert.True(acceptedSocket.Connected);
// Try to ensure that the elapsed timeout is reasonably correct
Assert.InRange(elapsed, Timeout * 0.75, Timeout * 1.5);
// Sometimes test machines run slowly
Assert.InRange(elapsed, Timeout * 0.75, Timeout * 2);
}
}
@@ -127,7 +128,8 @@ namespace System.Net.Sockets.Tests
Assert.True(acceptedSocket.Connected);
// Try to ensure that the elapsed timeout is reasonably correct
Assert.InRange(elapsed, Timeout * 0.5, Timeout * 2);
// Sometimes test machines run slowly
Assert.InRange(elapsed, Timeout * 0.5, Timeout * 3);
}
}
}

View File

@@ -2,20 +2,14 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Test.Common;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public class UnixDomainSocketTest
public partial class UnixDomainSocketTest
{
private readonly ITestOutputHelper _log;
@@ -32,411 +26,5 @@ namespace System.Net.Sockets.Tests
SocketException e = Assert.Throws<SocketException>(() => new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified));
Assert.Equal(SocketError.AddressFamilyNotSupported, e.SocketErrorCode);
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConnectAsyncUnixDomainSocketEndPoint success on Unix
public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_Success()
{
string path = null;
SocketTestServer server = null;
UnixDomainSocketEndPoint endPoint = null;
for (int attempt = 0; attempt < 5; attempt++)
{
path = GetRandomNonExistingFilePath();
endPoint = new UnixDomainSocketEndPoint(path);
try
{
server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, endPoint, ProtocolType.Unspecified);
break;
}
catch (SocketException)
{
//Path selection is contingent on a successful Bind().
//If it fails, the next iteration will try another path.
}
}
try
{
Assert.NotNull(server);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = endPoint;
args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true);
var complete = new TaskCompletionSource<bool>();
args.UserToken = complete;
using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
await complete.Task;
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Null(args.ConnectByNameError);
}
}
finally
{
server.Dispose();
try { File.Delete(path); }
catch { }
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConnectAsyncUnixDomainSocketEndPoint seccess on Unix
public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_NotServer()
{
string path = GetRandomNonExistingFilePath();
var endPoint = new UnixDomainSocketEndPoint(path);
try
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = endPoint;
args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true);
var complete = new TaskCompletionSource<bool>();
args.UserToken = complete;
using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
await complete.Task;
}
Assert.Equal(SocketError.AddressNotAvailable, args.SocketError);
}
}
finally
{
try { File.Delete(path); }
catch { }
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceive success for UnixDomainSocketEndPoint on Unix
public void Socket_SendReceive_Success()
{
string path = GetRandomNonExistingFilePath();
var endPoint = new UnixDomainSocketEndPoint(path);
try
{
using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
server.Bind(endPoint);
server.Listen(1);
client.Connect(endPoint);
using (Socket accepted = server.Accept())
{
var data = new byte[1];
for (int i = 0; i < 10; i++)
{
data[0] = (byte)i;
accepted.Send(data);
data[0] = 0;
Assert.Equal(1, client.Receive(data));
Assert.Equal(i, data[0]);
}
}
}
}
finally
{
try { File.Delete(path); }
catch { }
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceiveAsync success for UnixDomainSocketEndPoint on Unix
public async Task Socket_SendReceiveAsync_Success()
{
string path = GetRandomNonExistingFilePath();
var endPoint = new UnixDomainSocketEndPoint(path);
try
{
using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
server.Bind(endPoint);
server.Listen(1);
await client.ConnectAsync(endPoint);
using (Socket accepted = await server.AcceptAsync())
{
var data = new byte[1];
for (int i = 0; i < 10; i++)
{
data[0] = (byte)i;
await accepted.SendAsync(new ArraySegment<byte>(data), SocketFlags.None);
data[0] = 0;
Assert.Equal(1, await client.ReceiveAsync(new ArraySegment<byte>(data), SocketFlags.None));
Assert.Equal(i, data[0]);
}
}
}
}
finally
{
try { File.Delete(path); }
catch { }
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(5000, 1, 1)]
[InlineData(500, 18, 21)]
[InlineData(500, 21, 18)]
[InlineData(5, 128000, 64000)]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceiveAsync success for UnixDomainSocketEndPoint on Unix
public async Task Socket_SendReceiveAsync_PropagateToStream_Success(int iterations, int writeBufferSize, int readBufferSize)
{
var writeBuffer = new byte[writeBufferSize * iterations];
new Random().NextBytes(writeBuffer);
var readData = new MemoryStream();
string path = GetRandomNonExistingFilePath();
var endPoint = new UnixDomainSocketEndPoint(path);
try
{
using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
server.Bind(endPoint);
server.Listen(1);
Task<Socket> serverAccept = server.AcceptAsync();
await Task.WhenAll(serverAccept, client.ConnectAsync(endPoint));
Task clientReceives = Task.Run(async () =>
{
int bytesRead;
byte[] buffer = new byte[readBufferSize];
while ((bytesRead = await client.ReceiveAsync(new ArraySegment<byte>(buffer), SocketFlags.None)) > 0)
{
readData.Write(buffer, 0, bytesRead);
}
});
using (Socket accepted = await serverAccept)
{
for (int iter = 0; iter < iterations; iter++)
{
Task<int> sendTask = accepted.SendAsync(new ArraySegment<byte>(writeBuffer, iter * writeBufferSize, writeBufferSize), SocketFlags.None);
await await Task.WhenAny(clientReceives, sendTask);
Assert.Equal(writeBufferSize, await sendTask);
}
}
await clientReceives;
}
Assert.Equal(writeBuffer.Length, readData.Length);
Assert.Equal(writeBuffer, readData.ToArray());
}
finally
{
try { File.Delete(path); }
catch { }
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(false)]
[InlineData(true)]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConcurrentSendReceive success for UnixDomainSocketEndPoint on Unix
public void ConcurrentSendReceive(bool forceNonBlocking)
{
using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
const int Iters = 25;
byte[] sendData = new byte[Iters];
byte[] receiveData = new byte[sendData.Length];
new Random().NextBytes(sendData);
string path = GetRandomNonExistingFilePath();
server.Bind(new UnixDomainSocketEndPoint(path));
server.Listen(1);
Task<Socket> acceptTask = server.AcceptAsync();
client.Connect(new UnixDomainSocketEndPoint(path));
acceptTask.Wait();
Socket accepted = acceptTask.Result;
client.ForceNonBlocking(forceNonBlocking);
accepted.ForceNonBlocking(forceNonBlocking);
Task[] writes = new Task[Iters];
Task<int>[] reads = new Task<int>[Iters];
for (int i = 0; i < Iters; i++)
{
reads[i] = Task.Factory.StartNew(s => accepted.Receive(receiveData, (int)s, 1, SocketFlags.None), i,
CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
for (int i = 0; i < Iters; i++)
{
writes[i] = Task.Factory.StartNew(s => client.Send(sendData, (int)s, 1, SocketFlags.None), i,
CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
Task.WaitAll(writes);
Task.WaitAll(reads);
Assert.Equal(sendData.OrderBy(i => i), receiveData.OrderBy(i => i));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConcurrentSendReceive success for UnixDomainSocketEndPoint on Unix
public void ConcurrentSendReceiveAsync()
{
using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
const int Iters = 2048;
byte[] sendData = new byte[Iters];
byte[] receiveData = new byte[sendData.Length];
new Random().NextBytes(sendData);
string path = GetRandomNonExistingFilePath();
server.Bind(new UnixDomainSocketEndPoint(path));
server.Listen(1);
Task<Socket> acceptTask = server.AcceptAsync();
client.Connect(new UnixDomainSocketEndPoint(path));
acceptTask.Wait();
Socket accepted = acceptTask.Result;
Task[] writes = new Task[Iters];
Task<int>[] reads = new Task<int>[Iters];
for (int i = 0; i < Iters; i++)
{
writes[i] = client.SendAsync(new ArraySegment<byte>(sendData, i, 1), SocketFlags.None);
}
for (int i = 0; i < Iters; i++)
{
reads[i] = accepted.ReceiveAsync(new ArraySegment<byte>(receiveData, i, 1), SocketFlags.None);
}
Task.WaitAll(writes);
Task.WaitAll(reads);
Assert.Equal(sendData, receiveData);
}
}
private static string GetRandomNonExistingFilePath()
{
string result;
do
{
result = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
}
while (File.Exists(result));
return result;
}
private sealed class UnixDomainSocketEndPoint : EndPoint
{
private const AddressFamily EndPointAddressFamily = AddressFamily.Unix;
private static readonly Encoding s_pathEncoding = Encoding.UTF8;
private static readonly int s_nativePathOffset = 2; // = offsetof(struct sockaddr_un, sun_path). It's the same on Linux and OSX
private static readonly int s_nativePathLength = 91; // sockaddr_un.sun_path at http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_un.h.html, -1 for terminator
private static readonly int s_nativeAddressSize = s_nativePathOffset + s_nativePathLength;
private readonly string _path;
private readonly byte[] _encodedPath;
public UnixDomainSocketEndPoint(string path)
{
if (path == null)
{
throw new ArgumentNullException(nameof(path));
}
_path = path;
_encodedPath = s_pathEncoding.GetBytes(_path);
if (path.Length == 0 || _encodedPath.Length > s_nativePathLength)
{
throw new ArgumentOutOfRangeException(nameof(path));
}
}
internal UnixDomainSocketEndPoint(SocketAddress socketAddress)
{
if (socketAddress == null)
{
throw new ArgumentNullException(nameof(socketAddress));
}
if (socketAddress.Family != EndPointAddressFamily ||
socketAddress.Size > s_nativeAddressSize)
{
throw new ArgumentOutOfRangeException(nameof(socketAddress));
}
if (socketAddress.Size > s_nativePathOffset)
{
_encodedPath = new byte[socketAddress.Size - s_nativePathOffset];
for (int i = 0; i < _encodedPath.Length; i++)
{
_encodedPath[i] = socketAddress[s_nativePathOffset + i];
}
_path = s_pathEncoding.GetString(_encodedPath, 0, _encodedPath.Length);
}
else
{
_encodedPath = Array.Empty<byte>();
_path = string.Empty;
}
}
public override SocketAddress Serialize()
{
var result = new SocketAddress(AddressFamily.Unix, s_nativeAddressSize);
Debug.Assert(_encodedPath.Length + s_nativePathOffset <= result.Size, "Expected path to fit in address");
for (int index = 0; index < _encodedPath.Length; index++)
{
result[s_nativePathOffset + index] = _encodedPath[index];
}
result[s_nativePathOffset + _encodedPath.Length] = 0; // path must be null-terminated
return result;
}
public override EndPoint Create(SocketAddress socketAddress) => new UnixDomainSocketEndPoint(socketAddress);
public override AddressFamily AddressFamily => EndPointAddressFamily;
public override string ToString() => _path;
}
}
}

View File

@@ -0,0 +1,447 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Sockets.Tests
{
public partial class UnixDomainSocketTest
{
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // new UnixDomainSocketEndPoint should throw on Windows
public void UnixDomainSocketEndPoint_Throws_OnWindows()
{
Assert.Throws<PlatformNotSupportedException>(() => new UnixDomainSocketEndPoint("/path"));
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConnectAsyncUnixDomainSocketEndPoint success on Unix
public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_Success()
{
string path = null;
SocketTestServer server = null;
UnixDomainSocketEndPoint endPoint = null;
for (int attempt = 0; attempt < 5; attempt++)
{
path = GetRandomNonExistingFilePath();
endPoint = new UnixDomainSocketEndPoint(path);
try
{
server = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, endPoint, ProtocolType.Unspecified);
break;
}
catch (SocketException)
{
//Path selection is contingent on a successful Bind().
//If it fails, the next iteration will try another path.
}
}
try
{
Assert.NotNull(server);
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = endPoint;
args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true);
var complete = new TaskCompletionSource<bool>();
args.UserToken = complete;
using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
await complete.Task;
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Null(args.ConnectByNameError);
}
}
finally
{
server.Dispose();
try { File.Delete(path); }
catch { }
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConnectAsyncUnixDomainSocketEndPoint seccess on Unix
public async Task Socket_ConnectAsyncUnixDomainSocketEndPoint_NotServer()
{
string path = GetRandomNonExistingFilePath();
var endPoint = new UnixDomainSocketEndPoint(path);
try
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
args.RemoteEndPoint = endPoint;
args.Completed += (s, e) => ((TaskCompletionSource<bool>)e.UserToken).SetResult(true);
var complete = new TaskCompletionSource<bool>();
args.UserToken = complete;
using (Socket sock = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
bool willRaiseEvent = sock.ConnectAsync(args);
if (willRaiseEvent)
{
await complete.Task;
}
Assert.Equal(SocketError.AddressNotAvailable, args.SocketError);
}
}
finally
{
try { File.Delete(path); }
catch { }
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceive success for UnixDomainSocketEndPoint on Unix
public void Socket_SendReceive_Success()
{
string path = GetRandomNonExistingFilePath();
var endPoint = new UnixDomainSocketEndPoint(path);
try
{
using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
server.Bind(endPoint);
server.Listen(1);
client.Connect(endPoint);
using (Socket accepted = server.Accept())
{
var data = new byte[1];
for (int i = 0; i < 10; i++)
{
data[0] = (byte)i;
accepted.Send(data);
data[0] = 0;
Assert.Equal(1, client.Receive(data));
Assert.Equal(i, data[0]);
}
}
}
}
finally
{
try { File.Delete(path); }
catch { }
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceiveAsync success for UnixDomainSocketEndPoint on Unix
public async Task Socket_SendReceiveAsync_Success()
{
string path = GetRandomNonExistingFilePath();
var endPoint = new UnixDomainSocketEndPoint(path);
try
{
using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
server.Bind(endPoint);
server.Listen(1);
await client.ConnectAsync(endPoint);
using (Socket accepted = await server.AcceptAsync())
{
var data = new byte[1];
for (int i = 0; i < 10; i++)
{
data[0] = (byte)i;
await accepted.SendAsync(new ArraySegment<byte>(data), SocketFlags.None);
data[0] = 0;
Assert.Equal(1, await client.ReceiveAsync(new ArraySegment<byte>(data), SocketFlags.None));
Assert.Equal(i, data[0]);
}
}
}
}
finally
{
try { File.Delete(path); }
catch { }
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(5000, 1, 1)]
[InlineData(500, 18, 21)]
[InlineData(500, 21, 18)]
[InlineData(5, 128000, 64000)]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests SendReceiveAsync success for UnixDomainSocketEndPoint on Unix
public async Task Socket_SendReceiveAsync_PropagateToStream_Success(int iterations, int writeBufferSize, int readBufferSize)
{
var writeBuffer = new byte[writeBufferSize * iterations];
new Random().NextBytes(writeBuffer);
var readData = new MemoryStream();
string path = GetRandomNonExistingFilePath();
var endPoint = new UnixDomainSocketEndPoint(path);
try
{
using (var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (var client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
server.Bind(endPoint);
server.Listen(1);
Task<Socket> serverAccept = server.AcceptAsync();
await Task.WhenAll(serverAccept, client.ConnectAsync(endPoint));
Task clientReceives = Task.Run(async () =>
{
int bytesRead;
byte[] buffer = new byte[readBufferSize];
while ((bytesRead = await client.ReceiveAsync(new ArraySegment<byte>(buffer), SocketFlags.None)) > 0)
{
readData.Write(buffer, 0, bytesRead);
}
});
using (Socket accepted = await serverAccept)
{
for (int iter = 0; iter < iterations; iter++)
{
Task<int> sendTask = accepted.SendAsync(new ArraySegment<byte>(writeBuffer, iter * writeBufferSize, writeBufferSize), SocketFlags.None);
await await Task.WhenAny(clientReceives, sendTask);
Assert.Equal(writeBufferSize, await sendTask);
}
}
await clientReceives;
}
Assert.Equal(writeBuffer.Length, readData.Length);
Assert.Equal(writeBuffer, readData.ToArray());
}
finally
{
try { File.Delete(path); }
catch { }
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(false)]
[InlineData(true)]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConcurrentSendReceive success for UnixDomainSocketEndPoint on Unix
public async Task ConcurrentSendReceive(bool forceNonBlocking)
{
using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
const int Iters = 25;
byte[] sendData = new byte[Iters];
byte[] receiveData = new byte[sendData.Length];
new Random().NextBytes(sendData);
string path = GetRandomNonExistingFilePath();
server.Bind(new UnixDomainSocketEndPoint(path));
server.Listen(1);
Task<Socket> acceptTask = server.AcceptAsync();
client.Connect(new UnixDomainSocketEndPoint(path));
await acceptTask;
Socket accepted = acceptTask.Result;
client.ForceNonBlocking(forceNonBlocking);
accepted.ForceNonBlocking(forceNonBlocking);
Task[] writes = new Task[Iters];
Task<int>[] reads = new Task<int>[Iters];
for (int i = 0; i < Iters; i++)
{
reads[i] = Task.Factory.StartNew(s => accepted.Receive(receiveData, (int)s, 1, SocketFlags.None), i,
CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
for (int i = 0; i < Iters; i++)
{
writes[i] = Task.Factory.StartNew(s => client.Send(sendData, (int)s, 1, SocketFlags.None), i,
CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
await TestSettings.WhenAllOrAnyFailedWithTimeout(writes.Concat(reads).ToArray());
Assert.Equal(sendData.OrderBy(i => i), receiveData.OrderBy(i => i));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests ConcurrentSendReceive success for UnixDomainSocketEndPoint on Unix
public async Task ConcurrentSendReceiveAsync()
{
using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
const int Iters = 2048;
byte[] sendData = new byte[Iters];
byte[] receiveData = new byte[sendData.Length];
new Random().NextBytes(sendData);
string path = GetRandomNonExistingFilePath();
server.Bind(new UnixDomainSocketEndPoint(path));
server.Listen(1);
Task<Socket> acceptTask = server.AcceptAsync();
client.Connect(new UnixDomainSocketEndPoint(path));
await acceptTask;
Socket accepted = acceptTask.Result;
Task[] writes = new Task[Iters];
Task<int>[] reads = new Task<int>[Iters];
for (int i = 0; i < Iters; i++)
{
writes[i] = client.SendAsync(new ArraySegment<byte>(sendData, i, 1), SocketFlags.None);
}
for (int i = 0; i < Iters; i++)
{
reads[i] = accepted.ReceiveAsync(new ArraySegment<byte>(receiveData, i, 1), SocketFlags.None);
}
await TestSettings.WhenAllOrAnyFailedWithTimeout(writes.Concat(reads).ToArray());
Assert.Equal(sendData, receiveData);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Tests new UnixDomainSocketEndPoint throws the correct exception for invalid args
public void UnixDomainSocketEndPoint_InvalidPaths_Throws()
{
Assert.Throws<ArgumentNullException>(() => new UnixDomainSocketEndPoint(null));
Assert.Throws<ArgumentOutOfRangeException>(() => new UnixDomainSocketEndPoint(string.Empty));
int maxNativeSize = (int)typeof(UnixDomainSocketEndPoint)
.GetField("s_nativePathLength", BindingFlags.Static | BindingFlags.NonPublic)
.GetValue(null);
string invalidLengthString = new string('a', maxNativeSize + 1);
Assert.Throws<ArgumentOutOfRangeException>(() => new UnixDomainSocketEndPoint(invalidLengthString));
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix)]
[InlineData(false)]
[InlineData(true)]
public void UnixDomainSocketEndPoint_RemoteEndPointEqualsBindAddress(bool abstractAddress)
{
string serverAddress;
string clientAddress;
string expectedClientAddress;
if (abstractAddress)
{
// abstract socket addresses are a Linux feature.
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return;
}
// An abstract socket address starts with a zero byte.
serverAddress = '\0' + Guid.NewGuid().ToString();
clientAddress = '\0' + Guid.NewGuid().ToString();
expectedClientAddress = '@' + clientAddress.Substring(1);
}
else
{
serverAddress = GetRandomNonExistingFilePath();
clientAddress = GetRandomNonExistingFilePath();
expectedClientAddress = clientAddress;
}
try
{
using (Socket server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
server.Bind(new UnixDomainSocketEndPoint(serverAddress));
server.Listen(1);
using (Socket client = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
// Bind the client.
client.Bind(new UnixDomainSocketEndPoint(clientAddress));
client.Connect(new UnixDomainSocketEndPoint(serverAddress));
using (Socket acceptedClient = server.Accept())
{
// Verify the client address on the server.
EndPoint clientAddressOnServer = acceptedClient.RemoteEndPoint;
Assert.True(string.CompareOrdinal(expectedClientAddress, clientAddressOnServer.ToString()) == 0);
}
}
}
}
finally
{
if (!abstractAddress)
{
try { File.Delete(serverAddress); }
catch { }
try { File.Delete(clientAddress); }
catch { }
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix & ~TestPlatforms.Linux)] // Don't support abstract socket addresses.
public void UnixDomainSocketEndPoint_UsingAbstractSocketAddressOnUnsupported_Throws()
{
// An abstract socket address starts with a zero byte.
string address = '\0' + Guid.NewGuid().ToString();
// Bind
using (Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
Assert.ThrowsAny<SocketException>(() => socket.Bind(new UnixDomainSocketEndPoint(address)));
}
// Connect
using (Socket socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified))
{
Assert.ThrowsAny<SocketException>(() => socket.Connect(new UnixDomainSocketEndPoint(address)));
}
}
private static string GetRandomNonExistingFilePath()
{
string result;
do
{
result = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
}
while (File.Exists(result));
return result;
}
}
}

Some files were not shown because too many files have changed in this diff Show More