private IPPacketInformation GetNonDefaultIPPacketInformation() { const int ReceiveTimeout = 5000; using (var receiver = new Socket(SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(SocketType.Dgram, ProtocolType.Udp)) { int port = receiver.BindToAnonymousPort(IPAddress.Loopback); var waitHandle = new ManualResetEvent(false); SocketAsyncEventArgs receiveArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port), UserToken = waitHandle }; receiveArgs.SetBuffer(new byte[1], 0, 1); receiveArgs.Completed += (_, args) => ((ManualResetEvent)args.UserToken).Set(); Assert.True(receiver.ReceiveMessageFromAsync(receiveArgs)); sender.SendTo(new byte[1], new IPEndPoint(IPAddress.Loopback, port)); Assert.True(waitHandle.WaitOne(ReceiveTimeout)); return receiveArgs.ReceiveMessageFromPacketInfo; } }
private IPPacketInformation GetNonDefaultIPPacketInformation() { const int ReceiveTimeout = 5000; using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int port = receiver.BindToAnonymousPort(IPAddress.Loopback); var waitHandle = new ManualResetEvent(false); SocketAsyncEventArgs receiveArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port), UserToken = waitHandle }; receiveArgs.SetBuffer(new byte[1], 0, 1); receiveArgs.Completed += (_, args) => ((ManualResetEvent)args.UserToken).Set(); Assert.True(receiver.ReceiveMessageFromAsync(receiveArgs)); // Send a few packets, in case they aren't delivered reliably. for (int i = 0; i < Configuration.UDPRedundancy; i++) { sender.SendTo(new byte[1], new IPEndPoint(IPAddress.Loopback, port)); } Assert.True(waitHandle.WaitOne(ReceiveTimeout)); return receiveArgs.ReceiveMessageFromPacketInfo; } }
public void ReceiveTimesOut_Throws() { using (Socket localSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { using (Socket remoteSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = localSocket.BindToAnonymousPort(IPAddress.IPv6Loopback); localSocket.Listen(1); IAsyncResult localAsync = localSocket.BeginAccept(null, null); remoteSocket.Connect(IPAddress.IPv6Loopback, port); Socket acceptedSocket = localSocket.EndAccept(localAsync); acceptedSocket.ReceiveTimeout = 100; SocketException sockEx = Assert.Throws<SocketException>(() => { acceptedSocket.Receive(new byte[1]); }); Assert.Equal(SocketError.TimedOut, sockEx.SocketErrorCode); Assert.True(acceptedSocket.Connected); } } }
public void SelectRead_Multiple_Success() { using (var firstReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var secondReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int firstReceiverPort = firstReceiver.BindToAnonymousPort(IPAddress.Loopback); var firstReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, firstReceiverPort); int secondReceiverPort = secondReceiver.BindToAnonymousPort(IPAddress.Loopback); var secondReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, secondReceiverPort); sender.SendTo(new byte[1], SocketFlags.None, firstReceiverEndpoint); sender.SendTo(new byte[1], SocketFlags.None, secondReceiverEndpoint); var sw = Stopwatch.StartNew(); Assert.True(SpinWait.SpinUntil(() => { var list = new List<Socket> { firstReceiver, secondReceiver }; Socket.Select(list, null, null, Math.Max((int)(SelectSuccessTimeoutMicroseconds - (sw.Elapsed.TotalSeconds * 1000000)), 0)); Assert.True(list.Count <= 2); if (list.Count == 2) { Assert.Equal(firstReceiver, list[0]); Assert.Equal(secondReceiver, list[1]); return true; } return false; }, SelectSuccessTimeoutMicroseconds / 1000), "Failed to select both items within allotted time"); } }
public void Success() { ManualResetEvent completed = new ManualResetEvent(false); if (Socket.OSSupportsIPv4) { using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int port = receiver.BindToAnonymousPort(IPAddress.Loopback); receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sender.Bind(new IPEndPoint(IPAddress.Loopback, 0)); sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port)); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0); args.SetBuffer(new byte[1024], 0, 1024); args.Completed += OnCompleted; args.UserToken = completed; Assert.True(receiver.ReceiveMessageFromAsync(args)); Assert.True(completed.WaitOne(Configuration.PassingTestTimeout), "Timeout while waiting for connection"); Assert.Equal(1024, args.BytesTransferred); Assert.Equal(sender.LocalEndPoint, args.RemoteEndPoint); Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, args.ReceiveMessageFromPacketInfo.Address); sender.Dispose(); } } }
public void Success() { if (Socket.OSSupportsIPv4) { using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int port = receiver.BindToAnonymousPort(IPAddress.Loopback); receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sender.Bind(new IPEndPoint(IPAddress.Loopback, 0)); sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port)); IPPacketInformation packetInformation; SocketFlags flags = SocketFlags.None; EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); int len = receiver.ReceiveMessageFrom(new byte[1024], 0, 1024, ref flags, ref remoteEP, out packetInformation); Assert.Equal(1024, len); Assert.Equal(sender.LocalEndPoint, remoteEP); Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, packetInformation.Address); sender.Dispose(); } } }
public void SelectRead_Single_Timeout() { using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { receiver.BindToAnonymousPort(IPAddress.Loopback); var list = new List<Socket> { receiver }; Socket.Select(list, null, null, SelectTimeout); Assert.Equal(0, list.Count); } }
public void Socket_ReceiveFromDnsEndPoint_ArgumentException() { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int port = sock.BindToAnonymousPort(IPAddress.Loopback); EndPoint endpoint = new DnsEndPoint("localhost", port); Assert.Throws<ArgumentException>(() => { sock.ReceiveFrom(new byte[10], ref endpoint); }); } }
public void SelectRead_Single_Success() { using (var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int receiverPort = receiver.BindToAnonymousPort(IPAddress.Loopback); var receiverEndpoint = new IPEndPoint(IPAddress.Loopback, receiverPort); sender.SendTo(new byte[1], SocketFlags.None, receiverEndpoint); var list = new List<Socket> { receiver }; Socket.Select(list, null, null, SelectSuccessTimeoutMicroseconds); Assert.Equal(1, list.Count); Assert.Equal(receiver, list[0]); } }
public void SetLingerAfterServerClosed(bool linger, int timeout) { using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); { client.Connect(IPAddress.Loopback, port); server.Dispose(); Thread.Sleep(10); // give the server socket time to close client.LingerState = new LingerOption(linger, timeout); } } }
public void Shutdown_TCP_CLOSED_Success() { // NOTE: this value should technically be at least as long as the amount // of time that a TCP connection will stay in the TIME_WAIT state. // That value, however, is technically defined as 2 * MSL, which is // officially 4 minutes, and may differ between systems. In practice, // 5 seconds has proved to be long enough. const int TimeWaitTimeout = 5000; using (Socket server = new Socket(SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.IPv6Any); server.Listen(1); var args = new SocketAsyncEventArgs(); args.Completed += OnOperationCompleted; Assert.True(server.AcceptAsync(args)); client.Connect(IPAddress.IPv6Loopback, port); var buffer = new byte[] { 42 }; for (int i = 0; i < 32; i++) { int sent = client.Send(buffer); Assert.Equal(1, sent); } client.Shutdown(SocketShutdown.Send); int received = 0; do { received = client.Receive(buffer); } while (received != 0); // Wait for the underlying connection to transition from TIME_WAIT to // CLOSED. Task.Delay(TimeWaitTimeout).Wait(); client.Shutdown(SocketShutdown.Both); } }
public void SocketSendTimeout_Send_Success() { using (Socket localSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { using (Socket remoteSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = localSocket.BindToAnonymousPort(IPAddress.IPv6Loopback); localSocket.Listen(1); IAsyncResult localAsync = localSocket.BeginAccept(null, null); remoteSocket.Connect(IPAddress.IPv6Loopback, port); Socket acceptedSocket = localSocket.EndAccept(localAsync); acceptedSocket.SendTimeout = 100; // Note that Send almost never times out because it only has to copy the data to the native buffer. int bytes = acceptedSocket.Send(new byte[100]); Assert.Equal(100, bytes); Assert.True(acceptedSocket.Connected); } } }
public async Task Accept_Success(IPAddress listenAt) { using (Socket listen = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { int port = listen.BindToAnonymousPort(listenAt); listen.Listen(1); Task <Socket> acceptTask = AcceptAsync(listen); Assert.False(acceptTask.IsCompleted); using (Socket client = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { await ConnectAsync(client, new IPEndPoint(listenAt, port)); Socket accept = await acceptTask; Assert.NotNull(accept); Assert.True(accept.Connected); Assert.Equal(client.LocalEndPoint, accept.RemoteEndPoint); Assert.Equal(accept.LocalEndPoint, client.RemoteEndPoint); } } }
public async Task Accept_WithTargetSocket_Success() { if (!SupportsAcceptIntoExistingSocket) { return; } using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = listener.BindToAnonymousPort(IPAddress.Loopback); listener.Listen(1); Task <Socket> acceptTask = AcceptAsync(listener, server); client.Connect(IPAddress.Loopback, port); Socket accepted = await acceptTask; Assert.Same(server, accepted); Assert.True(accepted.Connected); } }
public async Task ReceiveSentMessages_Success(bool ipv4) { const int DatagramSize = 256; const int DatagramsToSend = 16; IPAddress address = ipv4 ? IPAddress.Loopback : IPAddress.IPv6Loopback; using Socket receiver = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp); using Socket sender = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp); receiver.SetSocketOption(ipv4 ? SocketOptionLevel.IP : SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, true); ConfigureNonBlocking(sender); ConfigureNonBlocking(receiver); receiver.BindToAnonymousPort(address); sender.BindToAnonymousPort(address); byte[] sendBuffer = new byte[DatagramSize]; byte[] receiveBuffer = new byte[DatagramSize]; Random rnd = new Random(0); IPEndPoint remoteEp = new IPEndPoint(ipv4 ? IPAddress.Any : IPAddress.IPv6Any, 0); for (int i = 0; i < DatagramsToSend; i++) { rnd.NextBytes(sendBuffer); sender.SendTo(sendBuffer, receiver.LocalEndPoint); SocketReceiveMessageFromResult result = await ReceiveMessageFromAsync(receiver, receiveBuffer, remoteEp); IPPacketInformation packetInformation = result.PacketInformation; Assert.Equal(DatagramSize, result.ReceivedBytes); AssertExtensions.SequenceEqual(sendBuffer, receiveBuffer); Assert.Equal(sender.LocalEndPoint, result.RemoteEndPoint); Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, packetInformation.Address); } }
public void AcceptAsync_IPv6_Success() { Assert.True(Capability.IPv6Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv6 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv6 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv6: Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } }
public async Task ClosedDuringOperation_Throws_ObjectDisposedExceptionOrSocketException(bool closeOrDispose) { if (UsesSync && PlatformDetection.IsOSX) { // [ActiveIssue("https://github.com/dotnet/runtime/issues/47342")] // On Mac, Close/Dispose hangs when invoked concurrently with a blocking UDP receive. return; } using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); socket.BindToAnonymousPort(IPAddress.Any); Task receiveTask = ReceiveFromAsync(socket, new byte[1], GetGetDummyTestEndpoint()); await Task.Delay(100); if (closeOrDispose) { socket.Close(); } else { socket.Dispose(); } if (UsesApm) { await Assert.ThrowsAsync <ObjectDisposedException>(() => receiveTask) .TimeoutAfter(CancellationTestTimeout); } else { SocketException ex = await Assert.ThrowsAsync <SocketException>(() => receiveTask) .TimeoutAfter(CancellationTestTimeout); SocketError expectedError = UsesSync ? SocketError.Interrupted : SocketError.OperationAborted; Assert.Equal(expectedError, ex.SocketErrorCode); } }
public void AcceptAsync_IPv6_Success() { Assert.True(Capability.IPv6Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv6 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv6 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv6: Timed out while waiting for connection"); Assert.Equal <SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } }
public async Task TcpAcceptSocket_WhenServerBoundToWildcardAddress_LocalEPIsSpecific() { using (Socket server = CreateTcpSocket()) using (Socket client = CreateTcpSocket()) { int serverPort = server.BindToAnonymousPort(Wildcard); Assert.Equal(Wildcard, GetLocalEPAddress(server)); // server -> wildcard before accept server.Listen(); Task <Socket> acceptTask = AcceptAsync(server); await ConnectAsync(client, new IPEndPoint(Loopback, serverPort)); Socket accept = await acceptTask; Assert.Equal(accept.RemoteEndPoint, client.LocalEndPoint); Assert.Equal(accept.LocalEndPoint, client.RemoteEndPoint); Assert.Equal(Wildcard, GetLocalEPAddress(server)); // server -> stays as wildcard Assert.Equal(Loopback, GetLocalEPAddress(accept)); // accept -> specific Assert.Equal(serverPort, GetLocalEPPort(accept)); } }
public void SelectRead_Multiple_Success() { using (var firstReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var secondReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int firstReceiverPort = firstReceiver.BindToAnonymousPort(IPAddress.Loopback); var firstReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, firstReceiverPort); int secondReceiverPort = secondReceiver.BindToAnonymousPort(IPAddress.Loopback); var secondReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, secondReceiverPort); sender.SendTo(new byte[1], SocketFlags.None, firstReceiverEndpoint); sender.SendTo(new byte[1], SocketFlags.None, secondReceiverEndpoint); var list = new List<Socket> { firstReceiver, secondReceiver }; Socket.Select(list, null, null, SelectSuccessTimeout); Assert.Equal(2, list.Count); Assert.Equal(firstReceiver, list[0]); Assert.Equal(secondReceiver, list[1]); } }
[PlatformSpecific(TestPlatforms.AnyUnix)] // Unix platforms don't yet support receiving data with AcceptAsync. public void AcceptAsync_WithReceiveBuffer_Failure() { // // Unix platforms don't yet support receiving data with AcceptAsync. // Assert.True(Capability.IPv4Support()); using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = new ManualResetEvent(false); byte[] buffer = new byte[1024]; acceptArgs.SetBuffer(buffer, 0, buffer.Length); Assert.Throws <PlatformNotSupportedException>(() => server.AcceptAsync(acceptArgs)); } }
public async Task AcceptReceive_Windows_Success() { if (!SupportsAcceptReceive) { // Currently only supported by APM and EAP return; } using Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); int port = listener.BindToAnonymousPort(IPAddress.Loopback); IPEndPoint listenerEndpoint = new IPEndPoint(IPAddress.Loopback, port); listener.Listen(100); var acceptTask = AcceptAsync(listener, 1); using Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sender.Connect(listenerEndpoint); sender.Send(new byte[] { 42 }); (_, byte[] recvBuffer) = await acceptTask; Assert.Equal(new byte[] { 42 }, recvBuffer); }
public void ReceiveTimesOut_Throws() { using (Socket localSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) using (Socket remoteSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = localSocket.BindToAnonymousPort(IPAddress.IPv6Loopback); localSocket.Listen(1); IAsyncResult localAsync = localSocket.BeginAccept(null, null); remoteSocket.Connect(IPAddress.IPv6Loopback, port); Socket acceptedSocket = localSocket.EndAccept(localAsync); acceptedSocket.ReceiveTimeout = TestSettings.FailingTestTimeout; SocketException sockEx = Assert.Throws <SocketException>(() => { acceptedSocket.Receive(new byte[1]); }); Assert.Equal(SocketError.TimedOut, sockEx.SocketErrorCode); Assert.True(acceptedSocket.Connected); } }
public async Task UdpSocket_WhenNotBound_LocalEPChangeToWildcardOnSendTo() { using (Socket receiver = CreateUdpSocket()) using (Socket sender = CreateUdpSocket()) { int receiverPort = receiver.BindToAnonymousPort(Wildcard); Assert.Null(sender.LocalEndPoint); // null before sendto var sendToEP = new IPEndPoint(Loopback, receiverPort); await SendToAsync(sender, new byte[] { 1, 2, 3 }, sendToEP); Assert.Equal(Wildcard, GetLocalEPAddress(sender)); // changes to wildcard after sendto byte[] buf = new byte[3]; EndPoint receiveFromEP = new IPEndPoint(Wildcard, 0); receiver.ReceiveFrom(buf, ref receiveFromEP); Assert.Equal(new byte[] { 1, 2, 3 }, buf); Assert.Equal(Loopback, ((IPEndPoint)receiveFromEP).Address); // received from specific address } }
[ConditionalFact(nameof(PlatformDetection) + "." + nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // https://github.com/Microsoft/BashOnWindows/issues/987 public void Success() { ManualResetEvent completed = new ManualResetEvent(false); if (Socket.OSSupportsIPv4) { using (Socket receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int port = receiver.BindToAnonymousPort(IPAddress.Loopback); receiver.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sender.Bind(new IPEndPoint(IPAddress.Loopback, 0)); for (int i = 0; i < TestSettings.UDPRedundancy; i++) { sender.SendTo(new byte[1024], new IPEndPoint(IPAddress.Loopback, port)); } SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(IPAddress.Any, 0); args.SetBuffer(new byte[1024], 0, 1024); args.Completed += OnCompleted; args.UserToken = completed; Assert.True(receiver.ReceiveMessageFromAsync(args)); Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timeout while waiting for connection"); Assert.Equal(1024, args.BytesTransferred); Assert.Equal(sender.LocalEndPoint, args.RemoteEndPoint); Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, args.ReceiveMessageFromPacketInfo.Address); sender.Dispose(); } } }
public void ReceiveTimesOut_Throws(bool forceNonBlocking) { using (Socket localSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) using (Socket remoteSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = localSocket.BindToAnonymousPort(IPAddress.IPv6Loopback); localSocket.Listen(1); IAsyncResult localAsync = localSocket.BeginAccept(null, null); remoteSocket.ForceNonBlocking(forceNonBlocking); remoteSocket.Connect(IPAddress.IPv6Loopback, port); Socket acceptedSocket = localSocket.EndAccept(localAsync); acceptedSocket.ReceiveTimeout = Timeout; acceptedSocket.ForceNonBlocking(forceNonBlocking); DateTime start = default(DateTime); SocketException sockEx = Assert.Throws <SocketException>(() => { start = DateTime.UtcNow; acceptedSocket.Receive(new byte[1]); }); double elapsed = (DateTime.UtcNow - start).TotalMilliseconds; Assert.Equal(SocketError.TimedOut, sockEx.SocketErrorCode); Assert.True(acceptedSocket.Connected); // Try to ensure that the elapsed timeout is reasonably correct // Sometimes test machines run slowly Assert.InRange(elapsed, Timeout * 0.75, Timeout * 2); } }
public void SelectRead_Multiple_Success() { using (var firstReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var secondReceiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int firstReceiverPort = firstReceiver.BindToAnonymousPort(IPAddress.Loopback); var firstReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, firstReceiverPort); int secondReceiverPort = secondReceiver.BindToAnonymousPort(IPAddress.Loopback); var secondReceiverEndpoint = new IPEndPoint(IPAddress.Loopback, secondReceiverPort); for (int i = 0; i < TestSettings.UDPRedundancy; i++) { sender.SendTo(new byte[1], SocketFlags.None, firstReceiverEndpoint); sender.SendTo(new byte[1], SocketFlags.None, secondReceiverEndpoint); } var sw = Stopwatch.StartNew(); Assert.True(SpinWait.SpinUntil(() => { var list = new List <Socket> { firstReceiver, secondReceiver }; Socket.Select(list, null, null, Math.Max((int)(SelectSuccessTimeoutMicroseconds - (sw.Elapsed.TotalSeconds * 1000000)), 0)); Assert.True(list.Count <= 2); if (list.Count == 2) { Assert.Equal(firstReceiver, list[0]); Assert.Equal(secondReceiver, list[1]); return(true); } return(false); }, SelectSuccessTimeoutMicroseconds / 1000), "Failed to select both items within allotted time"); } }
public void BindV6IPEndPoint_Success() { using (Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { socket.BindToAnonymousPort(IPAddress.IPv6Loopback); } }
public async Task SendRecv_Stream_TCP_MultipleConcurrentSends(IPAddress listenAt, bool useMultipleBuffers) { using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { byte[] sendData = new byte[5000000]; new Random(42).NextBytes(sendData); Func <byte[], int, int, byte[]> slice = (input, offset, count) => { var arr = new byte[count]; Array.Copy(input, offset, arr, 0, count); return(arr); }; server.BindToAnonymousPort(listenAt); server.Listen(1); EndPoint clientEndpoint = server.LocalEndPoint; using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { Task clientConnect = ConnectAsync(client, clientEndpoint); using (Socket remote = await AcceptAsync(server)) { await clientConnect; Task <int> send1, send2, send3; if (useMultipleBuffers) { var bufferList1 = new List <ArraySegment <byte> > { new ArraySegment <byte>(slice(sendData, 0, 1000000)), new ArraySegment <byte>(slice(sendData, 1000000, 1000000)) }; var bufferList2 = new List <ArraySegment <byte> > { new ArraySegment <byte>(slice(sendData, 2000000, 1000000)), new ArraySegment <byte>(slice(sendData, 3000000, 1000000)) }; var bufferList3 = new List <ArraySegment <byte> > { new ArraySegment <byte>(slice(sendData, 4000000, 1000000)) }; send1 = SendAsync(client, bufferList1); send2 = SendAsync(client, bufferList2); send3 = SendAsync(client, bufferList3); } else { var buffer1 = new ArraySegment <byte>(slice(sendData, 0, 2000000)); var buffer2 = new ArraySegment <byte>(slice(sendData, 2000000, 2000000)); var buffer3 = new ArraySegment <byte>(slice(sendData, 4000000, 1000000)); send1 = SendAsync(client, buffer1); send2 = SendAsync(client, buffer2); send3 = SendAsync(client, buffer3); } int receivedTotal = 0; int received; var receiveBuffer = new byte[sendData.Length]; while (receivedTotal < receiveBuffer.Length) { if ((received = await ReceiveAsync(remote, new ArraySegment <byte>(receiveBuffer, receivedTotal, receiveBuffer.Length - receivedTotal))) == 0) { break; } receivedTotal += received; } Assert.Equal(5000000, receivedTotal); if (GuaranteedSendOrdering) { Assert.Equal(sendData, receiveBuffer); } } } } }
private void BeginReceiveMessageFrom_Helper(IPAddress listenOn, IPAddress connectTo, bool expectedToTimeout = false) { using (Socket serverSocket = new Socket(SocketType.Dgram, ProtocolType.Udp)) { int port = serverSocket.BindToAnonymousPort(listenOn); EndPoint receivedFrom = new IPEndPoint(connectTo, port); SocketFlags socketFlags = SocketFlags.None; IPPacketInformation ipPacketInformation; IAsyncResult async = serverSocket.BeginReceiveMessageFrom(new byte[1], 0, 1, socketFlags, ref receivedFrom, null, null); // Behavior difference from Desktop: receivedFrom will _not_ change during the synchronous phase. // IPEndPoint remoteEndPoint = receivedFrom as IPEndPoint; // Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily); // Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address); SocketUdpClient client = new SocketUdpClient(_log, serverSocket, connectTo, port); bool success = async.AsyncWaitHandle.WaitOne(expectedToTimeout ? Configuration.FailingTestTimeout : Configuration.PassingTestTimeout); if (!success) { throw new TimeoutException(); } receivedFrom = new IPEndPoint(connectTo, port); int received = serverSocket.EndReceiveMessageFrom(async, ref socketFlags, ref receivedFrom, out ipPacketInformation); Assert.Equal(1, received); Assert.Equal<Type>(receivedFrom.GetType(), typeof(IPEndPoint)); IPEndPoint remoteEndPoint = receivedFrom as IPEndPoint; Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily); Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address); Assert.Equal(SocketFlags.None, socketFlags); Assert.NotNull(ipPacketInformation); Assert.Equal(connectTo, ipPacketInformation.Address); // TODO: Move to NetworkInformation tests. //Assert.Equal(NetworkInterface.IPv6LoopbackInterfaceIndex, ipPacketInformation.Interface); } }
private void ReceiveMessageFromAsync_Helper(IPAddress listenOn, IPAddress connectTo, bool expectedToTimeout = false) { using (Socket serverSocket = new Socket(SocketType.Dgram, ProtocolType.Udp)) { serverSocket.ReceiveTimeout = expectedToTimeout ? Configuration.FailingTestTimeout : Configuration.PassingTestTimeout; int port = serverSocket.BindToAnonymousPort(listenOn); ManualResetEvent waitHandle = new ManualResetEvent(false); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(connectTo, port); args.SetBuffer(new byte[1], 0, 1); args.Completed += AsyncCompleted; args.UserToken = waitHandle; bool async = serverSocket.ReceiveMessageFromAsync(args); Assert.True(async); SocketUdpClient client = new SocketUdpClient(_log, serverSocket, connectTo, port); if (!waitHandle.WaitOne(serverSocket.ReceiveTimeout)) { throw new TimeoutException(); } Assert.Equal(1, args.BytesTransferred); Assert.Equal<Type>(args.RemoteEndPoint.GetType(), typeof(IPEndPoint)); IPEndPoint remoteEndPoint = args.RemoteEndPoint as IPEndPoint; Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily); Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address); Assert.Equal(SocketFlags.None, args.SocketFlags); Assert.NotNull(args.ReceiveMessageFromPacketInfo); Assert.Equal(connectTo, args.ReceiveMessageFromPacketInfo.Address); // TODO: Move to NetworkInformation tests. // Assert.Equal(NetworkInterface.IPv6LoopbackInterfaceIndex, args.ReceiveMessageFromPacketInfo.Interface); } }
private void ReceiveFrom_Helper(IPAddress listenOn, IPAddress connectTo) { using (Socket serverSocket = new Socket(SocketType.Dgram, ProtocolType.Udp)) { serverSocket.ReceiveTimeout = 500; int port = serverSocket.BindToAnonymousPort(listenOn); SocketUdpClient client = new SocketUdpClient(_log, serverSocket, connectTo, port); EndPoint receivedFrom = new IPEndPoint(connectTo, port); int received = serverSocket.ReceiveFrom(new byte[1], ref receivedFrom); Assert.Equal(1, received); Assert.Equal<Type>(receivedFrom.GetType(), typeof(IPEndPoint)); IPEndPoint remoteEndPoint = receivedFrom as IPEndPoint; Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily); Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address); } }
private void ReceiveMessageFrom_Helper(IPAddress listenOn, IPAddress connectTo) { using (Socket serverSocket = new Socket(SocketType.Dgram, ProtocolType.Udp)) { serverSocket.ReceiveTimeout = 500; int port = serverSocket.BindToAnonymousPort(listenOn); EndPoint receivedFrom = new IPEndPoint(connectTo, port); SocketFlags socketFlags = SocketFlags.None; IPPacketInformation ipPacketInformation; int received = 0; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Throws<SocketException>(() => { // This is a false start. // http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.receivemessagefrom.aspx // "...the returned IPPacketInformation object will only be valid for packets which arrive at the // local computer after the socket option has been set. If a socket is sent packets between when // it is bound to a local endpoint (explicitly by the Bind method or implicitly by one of the Connect, // ConnectAsync, SendTo, or SendToAsync methods) and its first call to the ReceiveMessageFrom method, // calls to ReceiveMessageFrom method will return invalid IPPacketInformation objects for these packets." received = serverSocket.ReceiveMessageFrom(new byte[1], 0, 1, ref socketFlags, ref receivedFrom, out ipPacketInformation); }); } else { // *nix may throw either a SocketException or ArgumentException in this case, depending on how the IP stack // behaves w.r.t. dual-mode sockets bound to IPv6-specific addresses. Assert.ThrowsAny<Exception>(() => { received = serverSocket.ReceiveMessageFrom(new byte[1], 0, 1, ref socketFlags, ref receivedFrom, out ipPacketInformation); }); } SocketUdpClient client = new SocketUdpClient(_log, serverSocket, connectTo, port); receivedFrom = new IPEndPoint(connectTo, port); socketFlags = SocketFlags.None; received = serverSocket.ReceiveMessageFrom(new byte[1], 0, 1, ref socketFlags, ref receivedFrom, out ipPacketInformation); Assert.Equal(1, received); Assert.Equal<Type>(receivedFrom.GetType(), typeof(IPEndPoint)); IPEndPoint remoteEndPoint = receivedFrom as IPEndPoint; Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily); Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address); Assert.Equal(SocketFlags.None, socketFlags); Assert.NotNull(ipPacketInformation); Assert.Equal(connectTo, ipPacketInformation.Address); // TODO: Move to NetworkInformation tests. // Assert.Equal(NetworkInterface.IPv6LoopbackInterfaceIndex, ipPacketInformation.Interface); } }
private static void SendToRecvFrom_Datagram_UDP(IPAddress leftAddress, IPAddress rightAddress) { // TODO #5185: Harden against packet loss const int DatagramSize = 256; const int DatagramsToSend = 256; const int AckTimeout = 1000; const int TestTimeout = 30000; var left = new Socket(leftAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); left.BindToAnonymousPort(leftAddress); var right = new Socket(rightAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); right.BindToAnonymousPort(rightAddress); var leftEndpoint = (IPEndPoint)left.LocalEndPoint; var rightEndpoint = (IPEndPoint)right.LocalEndPoint; var receiverAck = new ManualResetEventSlim(); var senderAck = new ManualResetEventSlim(); var receivedChecksums = new uint?[DatagramsToSend]; var leftThread = new Thread(() => { using (left) { EndPoint remote = leftEndpoint.Create(leftEndpoint.Serialize()); var recvBuffer = new byte[DatagramSize]; for (int i = 0; i < DatagramsToSend; i++) { int received = left.ReceiveFrom(recvBuffer, SocketFlags.None, ref remote); Assert.Equal(DatagramSize, received); Assert.Equal(rightEndpoint, remote); int datagramId = (int)recvBuffer[0]; Assert.Null(receivedChecksums[datagramId]); receivedChecksums[datagramId] = Fletcher32.Checksum(recvBuffer, 0, received); receiverAck.Set(); Assert.True(senderAck.Wait(AckTimeout)); senderAck.Reset(); } } }); leftThread.Start(); var sentChecksums = new uint[DatagramsToSend]; using (right) { var random = new Random(); var sendBuffer = new byte[DatagramSize]; for (int i = 0; i < DatagramsToSend; i++) { random.NextBytes(sendBuffer); sendBuffer[0] = (byte)i; int sent = right.SendTo(sendBuffer, SocketFlags.None, leftEndpoint); Assert.True(receiverAck.Wait(AckTimeout)); receiverAck.Reset(); senderAck.Set(); Assert.Equal(DatagramSize, sent); sentChecksums[i] = Fletcher32.Checksum(sendBuffer, 0, sent); } } Assert.True(leftThread.Join(TestTimeout)); for (int i = 0; i < DatagramsToSend; i++) { Assert.NotNull(receivedChecksums[i]); Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]); } }
public void Success() { AutoResetEvent completed = new AutoResetEvent(false); if (Socket.OSSupportsIPv4) { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; // Not expecting the operation to finish synchronously as no client should be trying to connect. Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv4 Server: Waiting for clients."); Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); client.Connect(new IPEndPoint(IPAddress.Loopback, port)); _log.WriteLine("IPv4 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); Assert.Equal <SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv4 Accept Socket was not connected"); client.Dispose(); } } if (Socket.OSSupportsIPv6) { using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv6 Server: Waiting for clients."); Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); client.Connect(new IPEndPoint(IPAddress.IPv6Loopback, port)); _log.WriteLine("IPv6 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv6: Timed out while waiting for connection"); Assert.Equal <SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected"); //Assert.NotNull(args.AcceptSocket.m_RightEndPoint, "m_RightEndPoint was not set"); //Assert.Equal(client.LocalEndPoint, args.AcceptSocket.m_RemoteEndPoint, "m_RemoteEndPoint is wrong!"); client.Dispose(); } } }
public void SendRecvIovMaxTcp_Success() { // sending/receiving more than IOV_MAX segments causes EMSGSIZE on some platforms. // This is handled internally for stream sockets so this error shouldn't surface. // Use more than IOV_MAX (1024 on Linux & macOS) segments. const int SegmentCount = 2400; using (var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); var sendBuffer = new byte[SegmentCount]; Task serverProcessingTask = Task.Run(() => { using (Socket acceptSocket = server.Accept()) { // send data as SegmentCount (> IOV_MAX) 1-byte segments. var sendSegments = new List <ArraySegment <byte> >(); for (int i = 0; i < SegmentCount; i++) { sendBuffer[i] = (byte)i; sendSegments.Add(new ArraySegment <byte>(sendBuffer, i, 1)); } SocketError error; // Send blocks until all segments are sent. int bytesSent = acceptSocket.Send(sendSegments, SocketFlags.None, out error); Assert.Equal(SegmentCount, bytesSent); Assert.Equal(SocketError.Success, error); acceptSocket.Shutdown(SocketShutdown.Send); } }); using (var client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { client.Connect(server.LocalEndPoint); // receive data as 1-byte segments. var receiveBuffer = new byte[SegmentCount]; var receiveSegments = new List <ArraySegment <byte> >(); for (int i = 0; i < SegmentCount; i++) { receiveSegments.Add(new ArraySegment <byte>(receiveBuffer, i, 1)); } var bytesReceivedTotal = 0; do { SocketError error; // Receive can return up to IOV_MAX segments. int bytesReceived = client.Receive(receiveSegments, SocketFlags.None, out error); bytesReceivedTotal += bytesReceived; // Offset receiveSegments for next Receive. receiveSegments.RemoveRange(0, bytesReceived); Assert.NotEqual(0, bytesReceived); Assert.Equal(SocketError.Success, error); } while (bytesReceivedTotal != SegmentCount); AssertExtensions.Equal(sendBuffer, receiveBuffer); } } }
public async Task SendRecv_Stream_TCP_AlternateBufferAndBufferList(IPAddress listenAt) { const int BytesToSend = 123456; int bytesReceived = 0, bytesSent = 0; Fletcher32 receivedChecksum = new Fletcher32(), sentChecksum = new Fletcher32(); using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { server.BindToAnonymousPort(listenAt); server.Listen(1); Task serverProcessingTask = Task.Run(async() => { using (Socket remote = await AcceptAsync(server)) { byte[] recvBuffer1 = new byte[256], recvBuffer2 = new byte[256]; long iter = 0; while (true) { ArraySegment <byte> seg1 = new ArraySegment <byte>(recvBuffer1), seg2 = new ArraySegment <byte>(recvBuffer2); int received; switch (iter++ % 3) { case 0: // single buffer received = await ReceiveAsync(remote, seg1); break; case 1: // buffer list with a single buffer received = await ReceiveAsync(remote, new List <ArraySegment <byte> > { seg1 }); break; default: // buffer list with multiple buffers received = await ReceiveAsync(remote, new List <ArraySegment <byte> > { seg1, seg2 }); break; } if (received == 0) { break; } bytesReceived += received; receivedChecksum.Add(recvBuffer1, 0, Math.Min(received, recvBuffer1.Length)); if (received > recvBuffer1.Length) { receivedChecksum.Add(recvBuffer2, 0, received - recvBuffer1.Length); } } } }); EndPoint clientEndpoint = server.LocalEndPoint; using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { await ConnectAsync(client, clientEndpoint); var random = new Random(); byte[] sendBuffer1 = new byte[512], sendBuffer2 = new byte[512]; long iter = 0; for (int sent = 0, remaining = BytesToSend; remaining > 0; remaining -= sent) { random.NextBytes(sendBuffer1); random.NextBytes(sendBuffer2); int amountFromSendBuffer1 = Math.Min(sendBuffer1.Length, remaining); switch (iter++ % 3) { case 0: // single buffer sent = await SendAsync(client, new ArraySegment <byte>(sendBuffer1, 0, amountFromSendBuffer1)); break; case 1: // buffer list with a single buffer sent = await SendAsync(client, new List <ArraySegment <byte> > { new ArraySegment <byte>(sendBuffer1, 0, amountFromSendBuffer1) }); break; default: // buffer list with multiple buffers sent = await SendAsync(client, new List <ArraySegment <byte> > { new ArraySegment <byte>(sendBuffer1, 0, amountFromSendBuffer1), new ArraySegment <byte>(sendBuffer2, 0, Math.Min(sendBuffer2.Length, remaining - amountFromSendBuffer1)), }); break; } bytesSent += sent; sentChecksum.Add(sendBuffer1, 0, Math.Min(sent, sendBuffer1.Length)); if (sent > sendBuffer1.Length) { sentChecksum.Add(sendBuffer2, 0, sent - sendBuffer1.Length); } } client.Shutdown(SocketShutdown.Send); await serverProcessingTask; } Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); } }
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsSubsystemForLinux))] // [ActiveIssue("https://github.com/dotnet/runtime/issues/18258")] public async Task ReceiveIovMaxUdp_SuccessOrMessageSize() { // receiving more than IOV_MAX segments causes EMSGSIZE on some platforms. // We handle this for stream sockets by truncating. // This test verifies we are not truncating non-stream sockets. // Use more than IOV_MAX (1024 on Linux & macOS) segments // and less than Ethernet MTU. const int SegmentCount = 1200; var sender = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sender.BindToAnonymousPort(IPAddress.Loopback); var receiver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); receiver.Connect(sender.LocalEndPoint); // only receive from sender EndPoint receiverEndPoint = receiver.LocalEndPoint; Barrier b = new Barrier(2); Task receiveTask = Task.Run(() => { using (receiver) { var receiveBuffer = new byte[SegmentCount]; var receiveSegments = new List <ArraySegment <byte> >(); for (int i = 0; i < SegmentCount; i++) { receiveSegments.Add(new ArraySegment <byte>(receiveBuffer, i, 1)); } // receive data as SegmentCount (> IOV_MAX) 1-byte segments. SocketError error; // Signal we are ready to receive. b.SignalAndWait(); int bytesReceived = receiver.Receive(receiveSegments, SocketFlags.None, out error); if (error == SocketError.Success) { // platform received message in > IOV_MAX segments Assert.Equal(SegmentCount, bytesReceived); } else { // platform returns EMSGSIZE Assert.Equal(SocketError.MessageSize, error); Assert.Equal(0, bytesReceived); } } }); using (sender) { sender.Connect(receiverEndPoint); // Synchronize and wait for receiving task to be ready. b.SignalAndWait(); var sendBuffer = new byte[SegmentCount]; for (int i = 0; i < 10; i++) // UDPRedundancy { int bytesSent = sender.Send(sendBuffer); Assert.Equal(SegmentCount, bytesSent); await Task.WhenAny(receiveTask, Task.Delay(3)); if (receiveTask.IsCompleted) { break; } } } Assert.True(receiveTask.IsCompleted); await receiveTask; }
public async Task SendRecv_Stream_TCP_MultipleConcurrentReceives(IPAddress listenAt, bool useMultipleBuffers) { using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { server.BindToAnonymousPort(listenAt); server.Listen(1); EndPoint clientEndpoint = server.LocalEndPoint; using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { Task clientConnect = ConnectAsync(client, clientEndpoint); using (Socket remote = await AcceptAsync(server)) { await clientConnect; if (useMultipleBuffers) { byte[] buffer1 = new byte[1], buffer2 = new byte[1], buffer3 = new byte[1], buffer4 = new byte[1], buffer5 = new byte[1]; Task <int> receive1 = ReceiveAsync(client, new List <ArraySegment <byte> > { new ArraySegment <byte>(buffer1), new ArraySegment <byte>(buffer2) }); Task <int> receive2 = ReceiveAsync(client, new List <ArraySegment <byte> > { new ArraySegment <byte>(buffer3), new ArraySegment <byte>(buffer4) }); Task <int> receive3 = ReceiveAsync(client, new List <ArraySegment <byte> > { new ArraySegment <byte>(buffer5) }); await Task.WhenAll( SendAsync(remote, new ArraySegment <byte>(new byte[] { 1, 2, 3, 4, 5 })), receive1, receive2, receive3); Assert.True(receive1.Result == 1 || receive1.Result == 2, $"Expected 1 or 2, got {receive1.Result}"); Assert.True(receive2.Result == 1 || receive2.Result == 2, $"Expected 1 or 2, got {receive2.Result}"); Assert.Equal(1, receive3.Result); if (GuaranteedSendOrdering) { if (receive1.Result == 1 && receive2.Result == 1) { Assert.Equal(1, buffer1[0]); Assert.Equal(0, buffer2[0]); Assert.Equal(2, buffer3[0]); Assert.Equal(0, buffer4[0]); Assert.Equal(3, buffer5[0]); } else if (receive1.Result == 1 && receive2.Result == 2) { Assert.Equal(1, buffer1[0]); Assert.Equal(0, buffer2[0]); Assert.Equal(2, buffer3[0]); Assert.Equal(3, buffer4[0]); Assert.Equal(4, buffer5[0]); } else if (receive1.Result == 2 && receive2.Result == 1) { Assert.Equal(1, buffer1[0]); Assert.Equal(2, buffer2[0]); Assert.Equal(3, buffer3[0]); Assert.Equal(0, buffer4[0]); Assert.Equal(4, buffer5[0]); } else // receive1.Result == 2 && receive2.Result == 2 { Assert.Equal(1, buffer1[0]); Assert.Equal(2, buffer2[0]); Assert.Equal(3, buffer3[0]); Assert.Equal(4, buffer4[0]); Assert.Equal(5, buffer5[0]); } } } else { var buffer1 = new ArraySegment <byte>(new byte[1]); var buffer2 = new ArraySegment <byte>(new byte[1]); var buffer3 = new ArraySegment <byte>(new byte[1]); Task <int> receive1 = ReceiveAsync(client, buffer1); Task <int> receive2 = ReceiveAsync(client, buffer2); Task <int> receive3 = ReceiveAsync(client, buffer3); await Task.WhenAll( SendAsync(remote, new ArraySegment <byte>(new byte[] { 1, 2, 3 })), receive1, receive2, receive3); Assert.Equal(3, receive1.Result + receive2.Result + receive3.Result); if (GuaranteedSendOrdering) { Assert.Equal(1, buffer1.Array[0]); Assert.Equal(2, buffer2.Array[0]); Assert.Equal(3, buffer3.Array[0]); } } } } } }
private void DualModeConnect_AcceptAsync_Helper(IPAddress listenOn, IPAddress connectTo) { using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { int port = serverSocket.BindToAnonymousPort(listenOn); serverSocket.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += AsyncCompleted; ManualResetEvent waitHandle = new ManualResetEvent(false); args.UserToken = waitHandle; args.SocketError = SocketError.SocketError; _log.WriteLine(args.GetHashCode() + " SocketAsyncEventArgs with manual event " + waitHandle.GetHashCode()); if (!serverSocket.AcceptAsync(args)) { throw new SocketException((int)args.SocketError); } SocketClient client = new SocketClient(_log, serverSocket, connectTo, port); var waitHandles = new WaitHandle[2]; waitHandles[0] = waitHandle; waitHandles[1] = client.WaitHandle; int completedHandle = WaitHandle.WaitAny(waitHandles, Configuration.PassingTestTimeout); if (completedHandle == WaitHandle.WaitTimeout) { throw new TimeoutException("Timed out while waiting for either of client and server connections..."); } if (completedHandle == 1) // Client finished { if (client.Error != SocketError.Success) { // Client SocketException throw new SocketException((int)client.Error); } if (!waitHandle.WaitOne(5000)) // Now wait for the server. { throw new TimeoutException("Timed out while waiting for the server accept..."); } } _log.WriteLine(args.SocketError.ToString()); if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } Socket clientSocket = args.AcceptSocket; Assert.NotNull(clientSocket); Assert.True(clientSocket.Connected); AssertDualModeEnabled(clientSocket, listenOn); Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily); if (connectTo == IPAddress.Loopback) { Assert.Contains(((IPEndPoint)clientSocket.LocalEndPoint).Address, ValidIPv6Loopbacks); } else { Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address); } clientSocket.Dispose(); } }
private static void SendToRecvFromAsync_Datagram_UDP(IPAddress leftAddress, IPAddress rightAddress) { const int DatagramSize = 256; const int DatagramsToSend = 256; const int AckTimeout = 1000; const int TestTimeout = 30000; var left = new Socket(leftAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); var leftEventArgs = new SocketAsyncEventArgs(); left.BindToAnonymousPort(leftAddress); var right = new Socket(rightAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); var rightEventArgs = new SocketAsyncEventArgs(); right.BindToAnonymousPort(rightAddress); var leftEndpoint = (IPEndPoint)left.LocalEndPoint; var rightEndpoint = (IPEndPoint)right.LocalEndPoint; var receiverAck = new ManualResetEventSlim(); var senderAck = new ManualResetEventSlim(); EndPoint receiveRemote = leftEndpoint.Create(leftEndpoint.Serialize()); var receiverFinished = new TaskCompletionSource <bool>(); var receivedChecksums = new uint?[DatagramsToSend]; var receiveBuffer = new byte[DatagramSize]; int receivedDatagrams = -1; Action <int, EndPoint> receiveHandler = null; receiveHandler = (received, remote) => { if (receivedDatagrams != -1) { Assert.Equal(DatagramSize, received); Assert.Equal(rightEndpoint, remote); int datagramId = (int)receiveBuffer[0]; Assert.Null(receivedChecksums[datagramId]); receivedChecksums[datagramId] = Fletcher32.Checksum(receiveBuffer, 0, received); receiverAck.Set(); Assert.True(senderAck.Wait(AckTimeout)); senderAck.Reset(); receivedDatagrams++; if (receivedDatagrams == DatagramsToSend) { left.Dispose(); receiverFinished.SetResult(true); return; } } else { receivedDatagrams = 0; } left.ReceiveFromAsync(leftEventArgs, receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, receiveRemote, receiveHandler); }; receiveHandler(0, null); var random = new Random(); var sentChecksums = new uint[DatagramsToSend]; var sendBuffer = new byte[DatagramSize]; int sentDatagrams = -1; Action <int> sendHandler = null; sendHandler = sent => { if (sentDatagrams != -1) { Assert.True(receiverAck.Wait(AckTimeout)); receiverAck.Reset(); senderAck.Set(); Assert.Equal(DatagramSize, sent); sentChecksums[sentDatagrams] = Fletcher32.Checksum(sendBuffer, 0, sent); sentDatagrams++; if (sentDatagrams == DatagramsToSend) { right.Dispose(); return; } } else { sentDatagrams = 0; } random.NextBytes(sendBuffer); sendBuffer[0] = (byte)sentDatagrams; right.SendToAsync(rightEventArgs, sendBuffer, 0, sendBuffer.Length, SocketFlags.None, leftEndpoint, sendHandler); }; sendHandler(0); Assert.True(receiverFinished.Task.Wait(TestTimeout)); for (int i = 0; i < DatagramsToSend; i++) { Assert.NotNull(receivedChecksums[i]); Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]); } }
private static void SendRecv_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers) { const int BytesToSend = 123456; const int ListenBacklog = 1; const int LingerTime = 10; const int TestTimeout = 30000; var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp); server.BindToAnonymousPort(listenAt); server.Listen(ListenBacklog); int bytesReceived = 0; var receivedChecksum = new Fletcher32(); var serverThread = new Thread(() => { using (server) { Socket remote = server.Accept(); Assert.NotNull(remote); using (remote) { if (!useMultipleBuffers) { var recvBuffer = new byte[256]; for (;;) { int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None); if (received == 0) { break; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } } else { var recvBuffers = new List <ArraySegment <byte> > { new ArraySegment <byte>(new byte[123]), 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 (;;) { int received = remote.Receive(recvBuffers, SocketFlags.None); if (received == 0) { break; } bytesReceived += received; for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++) { ArraySegment <byte> buffer = recvBuffers[i]; int toAdd = Math.Min(buffer.Count, remaining); receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd); remaining -= toAdd; } } } } } }); serverThread.Start(); EndPoint clientEndpoint = server.LocalEndPoint; var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); client.Connect(clientEndpoint); int bytesSent = 0; var sentChecksum = new Fletcher32(); using (client) { var random = new Random(); if (!useMultipleBuffers) { var sendBuffer = new byte[512]; for (int sent = 0, remaining = BytesToSend; remaining > 0; remaining -= sent) { random.NextBytes(sendBuffer); sent = client.Send(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None); bytesSent += sent; sentChecksum.Add(sendBuffer, 0, sent); } } else { var sendBuffers = new List <ArraySegment <byte> > { new ArraySegment <byte>(new byte[23]), new ArraySegment <byte>(new byte[256], 2, 100), new ArraySegment <byte>(new byte[1], 0, 0), new ArraySegment <byte>(new byte[64], 9, 9) }; for (int sent = 0, toSend = BytesToSend; toSend > 0; toSend -= sent) { for (int i = 0; i < sendBuffers.Count; i++) { random.NextBytes(sendBuffers[i].Array); } sent = client.Send(sendBuffers, SocketFlags.None); bytesSent += sent; for (int i = 0, remaining = sent; i < sendBuffers.Count && remaining > 0; i++) { ArraySegment <byte> buffer = sendBuffers[i]; int toAdd = Math.Min(buffer.Count, remaining); sentChecksum.Add(buffer.Array, buffer.Offset, toAdd); remaining -= toAdd; } } } client.LingerState = new LingerOption(true, LingerTime); } Assert.True(serverThread.Join(TestTimeout), "Completed within allowed time"); Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); }
public async Task SendRecv_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers) { const int BytesToSend = 123456, ListenBacklog = 1, LingerTime = 1; int bytesReceived = 0, bytesSent = 0; Fletcher32 receivedChecksum = new Fletcher32(), sentChecksum = new Fletcher32(); using (var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { server.BindToAnonymousPort(listenAt); server.Listen(ListenBacklog); Task serverProcessingTask = Task.Run(async() => { using (Socket remote = await AcceptAsync(server)) { if (!useMultipleBuffers) { var recvBuffer = new byte[256]; for (;;) { int received = await ReceiveAsync(remote, new ArraySegment <byte>(recvBuffer)); if (received == 0) { break; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } } else { var recvBuffers = new List <ArraySegment <byte> > { new ArraySegment <byte>(new byte[123]), 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 (;;) { int received = await ReceiveAsync(remote, recvBuffers); if (received == 0) { break; } bytesReceived += received; for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++) { ArraySegment <byte> buffer = recvBuffers[i]; int toAdd = Math.Min(buffer.Count, remaining); receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd); remaining -= toAdd; } } } } }); EndPoint clientEndpoint = server.LocalEndPoint; using (var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { await ConnectAsync(client, clientEndpoint); var random = new Random(); if (!useMultipleBuffers) { var sendBuffer = new byte[512]; for (int sent = 0, remaining = BytesToSend; remaining > 0; remaining -= sent) { random.NextBytes(sendBuffer); sent = await SendAsync(client, new ArraySegment <byte>(sendBuffer, 0, Math.Min(sendBuffer.Length, remaining))); bytesSent += sent; sentChecksum.Add(sendBuffer, 0, sent); } } else { var sendBuffers = new List <ArraySegment <byte> > { new ArraySegment <byte>(new byte[23]), new ArraySegment <byte>(new byte[256], 2, 100), new ArraySegment <byte>(new byte[1], 0, 0), new ArraySegment <byte>(new byte[64], 9, 9) }; for (int sent = 0, toSend = BytesToSend; toSend > 0; toSend -= sent) { for (int i = 0; i < sendBuffers.Count; i++) { random.NextBytes(sendBuffers[i].Array); } sent = await SendAsync(client, sendBuffers); bytesSent += sent; for (int i = 0, remaining = sent; i < sendBuffers.Count && remaining > 0; i++) { ArraySegment <byte> buffer = sendBuffers[i]; int toAdd = Math.Min(buffer.Count, remaining); sentChecksum.Add(buffer.Array, buffer.Offset, toAdd); remaining -= toAdd; } } } client.LingerState = new LingerOption(true, LingerTime); client.Shutdown(SocketShutdown.Send); await serverProcessingTask; } Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); } }
private void Accept_Helper(IPAddress listenOn, IPAddress connectTo) { using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { int port = serverSocket.BindToAnonymousPort(listenOn); serverSocket.Listen(1); SocketClient client = new SocketClient(_log, serverSocket, connectTo, port); Socket clientSocket = serverSocket.Accept(); Assert.True(clientSocket.Connected); AssertDualModeEnabled(clientSocket, listenOn); Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily); } }
public void Socket_ReceiveFromDnsEndPoint_Throws() { // "The parameter remoteEP must not be of type DnsEndPoint." using (Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp)) { int port = socket.BindToAnonymousPort(IPAddress.IPv6Loopback); EndPoint receivedFrom = new DnsEndPoint("localhost", port, AddressFamily.InterNetworkV6); Assert.Throws<ArgumentException>(() => { int received = socket.ReceiveFrom(new byte[1], ref receivedFrom); }); } }
public async Task IncludeFile_Success(IPAddress listenAt, bool sendPreAndPostBuffers, int bytesToSend) { const int ListenBacklog = 1; const int TestTimeout = 30000; // Create file to send byte[] preBuffer; byte[] postBuffer; Fletcher32 sentChecksum; using TempFile tempFile = CreateFileToSend(bytesToSend, sendPreAndPostBuffers, out preBuffer, out postBuffer, out sentChecksum); // Start server var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp); server.BindToAnonymousPort(listenAt); Listen(server, ListenBacklog); // Configures NonBlocking behavior int bytesReceived = 0; var receivedChecksum = new Fletcher32(); var serverTask = Task.Run(() => { using (server) { Socket remote = server.Accept(); Assert.NotNull(remote); using (remote) { var recvBuffer = new byte[256]; while (true) { int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None); if (received == 0) { break; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } } } }); // Run client EndPoint serverEndpoint = server.LocalEndPoint; using (var client = new Socket(serverEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp)) { await ConnectAsync(client, serverEndpoint); // Configures NonBlocking behavior await SendFileAsync(client, tempFile.Path, preBuffer, postBuffer, TransmitFileOptions.UseDefaultWorkerThread); client.Shutdown(SocketShutdown.Send); } await serverTask.WaitAsync(TimeSpan.FromMilliseconds(TestTimeout)); Assert.Equal(bytesToSend, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); }
private void ReceiveFromAsync_Helper(IPAddress listenOn, IPAddress connectTo, bool expectedToTimeout = false) { using (Socket serverSocket = new Socket(SocketType.Dgram, ProtocolType.Udp)) { int port = serverSocket.BindToAnonymousPort(listenOn); ManualResetEvent waitHandle = new ManualResetEvent(false); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(listenOn, port); args.SetBuffer(new byte[1], 0, 1); args.UserToken = waitHandle; args.Completed += AsyncCompleted; bool async = serverSocket.ReceiveFromAsync(args); SocketUdpClient client = new SocketUdpClient(_log, serverSocket, connectTo, port); if (async && !waitHandle.WaitOne(expectedToTimeout ? Configuration.FailingTestTimeout : Configuration.PassingTestTimeout)) { throw new TimeoutException(); } if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } Assert.Equal(1, args.BytesTransferred); Assert.Equal<Type>(args.RemoteEndPoint.GetType(), typeof(IPEndPoint)); IPEndPoint remoteEndPoint = args.RemoteEndPoint as IPEndPoint; Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily); Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address); } }
private static void SendToRecvFromAPM_Datagram_UDP(IPAddress leftAddress, IPAddress rightAddress) { // TODO #5185: Harden against packet loss const int DatagramSize = 256; const int DatagramsToSend = 256; const int AckTimeout = 1000; const int TestTimeout = 30000; var left = new Socket(leftAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); left.BindToAnonymousPort(leftAddress); var right = new Socket(rightAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); right.BindToAnonymousPort(rightAddress); var leftEndpoint = (IPEndPoint)left.LocalEndPoint; var rightEndpoint = (IPEndPoint)right.LocalEndPoint; var receiverAck = new ManualResetEventSlim(); var senderAck = new ManualResetEventSlim(); EndPoint receiveRemote = leftEndpoint.Create(leftEndpoint.Serialize()); var receiverFinished = new TaskCompletionSource<bool>(); var receivedChecksums = new uint?[DatagramsToSend]; var receiveBuffer = new byte[DatagramSize]; int receivedDatagrams = -1; Action<int, EndPoint> receiveHandler = null; receiveHandler = (received, remote) => { try { if (receivedDatagrams != -1) { Assert.Equal(DatagramSize, received); Assert.Equal(rightEndpoint, remote); int datagramId = (int)receiveBuffer[0]; Assert.Null(receivedChecksums[datagramId]); receivedChecksums[datagramId] = Fletcher32.Checksum(receiveBuffer, 0, received); receiverAck.Set(); Assert.True(senderAck.Wait(AckTimeout)); senderAck.Reset(); receivedDatagrams++; if (receivedDatagrams == DatagramsToSend) { left.Dispose(); receiverFinished.SetResult(true); return; } } else { receivedDatagrams = 0; } left.ReceiveFromAPM(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, receiveRemote, receiveHandler); } catch (Exception ex) { receiverFinished.SetException(ex); } }; receiveHandler(0, null); var random = new Random(); var senderFinished = new TaskCompletionSource<bool>(); var sentChecksums = new uint[DatagramsToSend]; var sendBuffer = new byte[DatagramSize]; int sentDatagrams = -1; Action<int> sendHandler = null; sendHandler = sent => { try { if (sentDatagrams != -1) { Assert.True(receiverAck.Wait(AckTimeout)); receiverAck.Reset(); senderAck.Set(); Assert.Equal(DatagramSize, sent); sentChecksums[sentDatagrams] = Fletcher32.Checksum(sendBuffer, 0, sent); sentDatagrams++; if (sentDatagrams == DatagramsToSend) { right.Dispose(); senderFinished.SetResult(true); return; } } else { sentDatagrams = 0; } random.NextBytes(sendBuffer); sendBuffer[0] = (byte)sentDatagrams; right.SendToAPM(sendBuffer, 0, sendBuffer.Length, SocketFlags.None, leftEndpoint, sendHandler); } catch (Exception ex) { senderFinished.SetException(ex); } }; sendHandler(0); Assert.True(receiverFinished.Task.Wait(TestTimeout)); Assert.True(senderFinished.Task.Wait(TestTimeout)); for (int i = 0; i < DatagramsToSend; i++) { Assert.NotNull(receivedChecksums[i]); Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]); } }
// "The parameter remoteEP must not be of type DnsEndPoint." public void Socket_BeginReceiveMessageFromDnsEndPoint_Throws() { using (Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp)) { int port = socket.BindToAnonymousPort(IPAddress.IPv6Loopback); EndPoint receivedFrom = new DnsEndPoint("localhost", port, AddressFamily.InterNetworkV6); SocketFlags socketFlags = SocketFlags.None; Assert.Throws<ArgumentException>(() => { socket.BeginReceiveMessageFrom(new byte[1], 0, 1, socketFlags, ref receivedFrom, null, null); }); } }
private void DualModeConnect_AcceptAsync_Helper(IPAddress listenOn, IPAddress connectTo) { using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { int port = serverSocket.BindToAnonymousPort(listenOn); serverSocket.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += AsyncCompleted; ManualResetEvent waitHandle = new ManualResetEvent(false); args.UserToken = waitHandle; args.SocketError = SocketError.SocketError; _log.WriteLine(args.GetHashCode() + " SocketAsyncEventArgs with manual event " + waitHandle.GetHashCode()); if (!serverSocket.AcceptAsync(args)) { throw new SocketException((int)args.SocketError); } SocketClient client = new SocketClient(_log, serverSocket, connectTo, port); var waitHandles = new WaitHandle[2]; waitHandles[0] = waitHandle; waitHandles[1] = client.WaitHandle; int completedHandle = WaitHandle.WaitAny(waitHandles, 5000); if (completedHandle == WaitHandle.WaitTimeout) { throw new TimeoutException("Timed out while waiting for either of client and server connections..."); } if (completedHandle == 1) // Client finished { if (client.Error != SocketError.Success) { // Client SocketException throw new SocketException((int)client.Error); } if (!waitHandle.WaitOne(5000)) // Now wait for the server. { throw new TimeoutException("Timed out while waiting for the server accept..."); } } _log.WriteLine(args.SocketError.ToString()); if (args.SocketError != SocketError.Success) { throw new SocketException((int)args.SocketError); } Socket clientSocket = args.AcceptSocket; Assert.NotNull(clientSocket); Assert.True(clientSocket.Connected); Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily); if (connectTo == IPAddress.Loopback) { Assert.Contains(((IPEndPoint)clientSocket.LocalEndPoint).Address, ValidIPv6Loopbacks); } else { Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address); } clientSocket.Dispose(); } }
// "The parameter remoteEP must not be of type DnsEndPoint." public void Socket_ReceiveMessageFromAsyncDnsEndPoint_Throws() { using (Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp)) { int port = socket.BindToAnonymousPort(IPAddress.IPv6Loopback); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", port, AddressFamily.InterNetworkV6); args.SetBuffer(new byte[1], 0, 1); Assert.Throws<ArgumentException>(() => { socket.ReceiveMessageFromAsync(args); }); } }
public void Success_EventArgs(bool ipv4, int bufferMode) { AddressFamily family; IPAddress loopback, any; SocketOptionLevel level; if (ipv4) { if (!Socket.OSSupportsIPv4) { return; } family = AddressFamily.InterNetwork; loopback = IPAddress.Loopback; any = IPAddress.Any; level = SocketOptionLevel.IP; } else { if (!Socket.OSSupportsIPv6) { return; } family = AddressFamily.InterNetworkV6; loopback = IPAddress.IPv6Loopback; any = IPAddress.IPv6Any; level = SocketOptionLevel.IPv6; } using (var receiver = new Socket(family, SocketType.Dgram, ProtocolType.Udp)) using (var sender = new Socket(family, SocketType.Dgram, ProtocolType.Udp)) using (var saea = new SocketAsyncEventArgs()) { int port = receiver.BindToAnonymousPort(loopback); receiver.SetSocketOption(level, SocketOptionName.PacketInformation, true); sender.Bind(new IPEndPoint(loopback, 0)); saea.RemoteEndPoint = new IPEndPoint(any, 0); switch (bufferMode) { case 0: // single buffer saea.SetBuffer(new byte[1024], 0, 1024); break; case 1: // single buffer in buffer list saea.BufferList = new List <ArraySegment <byte> > { new ArraySegment <byte>(new byte[1024]) }; break; case 2: // multiple buffers in buffer list saea.BufferList = new List <ArraySegment <byte> > { new ArraySegment <byte>(new byte[512]), new ArraySegment <byte>(new byte[512]) }; break; } var mres = new ManualResetEventSlim(); saea.Completed += delegate { mres.Set(); }; bool pending = receiver.ReceiveMessageFromAsync(saea); for (int i = 0; i < TestSettings.UDPRedundancy; i++) { sender.SendTo(new byte[1024], new IPEndPoint(loopback, port)); } if (pending) { Assert.True(mres.Wait(30000), "Expected operation to complete within timeout"); } Assert.Equal(1024, saea.BytesTransferred); Assert.Equal(sender.LocalEndPoint, saea.RemoteEndPoint); Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, saea.ReceiveMessageFromPacketInfo.Address); } }
[Fact] // Base Case; BSoD on Win7, Win8 with IPv4 uninstalled public void BindMappedV4IPEndPoint_Success() { using (Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { socket.BindToAnonymousPort(IPAddress.Loopback.MapToIPv6()); } }
private static void SendRecvAsync_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers) { const int BytesToSend = 123456; const int ListenBacklog = 1; const int LingerTime = 10; const int TestTimeout = 30000; var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp); server.BindToAnonymousPort(listenAt); server.Listen(ListenBacklog); var serverFinished = new TaskCompletionSource <bool>(); int bytesReceived = 0; var receivedChecksum = new Fletcher32(); var serverEventArgs = new SocketAsyncEventArgs(); server.AcceptAsync(serverEventArgs, remote => { Action <int> recvHandler = null; bool first = true; if (!useMultipleBuffers) { var recvBuffer = new byte[256]; recvHandler = received => { if (!first) { if (received == 0) { remote.Dispose(); server.Dispose(); serverFinished.SetResult(true); return; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } else { first = false; } remote.ReceiveAsync(serverEventArgs, recvBuffer, 0, recvBuffer.Length, SocketFlags.None, recvHandler); }; } else { var recvBuffers = new List <ArraySegment <byte> > { new ArraySegment <byte>(new byte[123]), new ArraySegment <byte>(new byte[256], 2, 100), new ArraySegment <byte>(new byte[1], 0, 0), new ArraySegment <byte>(new byte[64], 9, 33) }; recvHandler = received => { if (!first) { if (received == 0) { remote.Dispose(); server.Dispose(); serverFinished.SetResult(true); return; } bytesReceived += received; for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++) { ArraySegment <byte> buffer = recvBuffers[i]; int toAdd = Math.Min(buffer.Count, remaining); receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd); remaining -= toAdd; } } else { first = false; } remote.ReceiveAsync(serverEventArgs, recvBuffers, SocketFlags.None, recvHandler); }; } recvHandler(0); }); EndPoint clientEndpoint = server.LocalEndPoint; var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); int bytesSent = 0; var sentChecksum = new Fletcher32(); var clientEventArgs = new SocketAsyncEventArgs(); client.ConnectAsync(clientEventArgs, clientEndpoint, () => { Action <int> sendHandler = null; var random = new Random(); var remaining = BytesToSend; bool first = true; if (!useMultipleBuffers) { var sendBuffer = new byte[512]; sendHandler = sent => { if (!first) { bytesSent += sent; sentChecksum.Add(sendBuffer, 0, sent); remaining -= sent; Assert.True(remaining >= 0); if (remaining == 0 || sent == 0) { client.LingerState = new LingerOption(true, LingerTime); client.Dispose(); return; } } else { first = false; } random.NextBytes(sendBuffer); client.SendAsync(clientEventArgs, sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None, sendHandler); }; } else { var sendBuffers = new List <ArraySegment <byte> > { new ArraySegment <byte>(new byte[23]), new ArraySegment <byte>(new byte[256], 2, 100), new ArraySegment <byte>(new byte[1], 0, 0), new ArraySegment <byte>(new byte[64], 9, 9) }; sendHandler = sent => { if (!first) { bytesSent += sent; for (int i = 0, r = sent; i < sendBuffers.Count && r > 0; i++) { ArraySegment <byte> buffer = sendBuffers[i]; int toAdd = Math.Min(buffer.Count, r); sentChecksum.Add(buffer.Array, buffer.Offset, toAdd); r -= toAdd; } remaining -= sent; if (remaining <= 0 || sent == 0) { client.LingerState = new LingerOption(true, LingerTime); client.Dispose(); return; } } else { first = false; } for (int i = 0; i < sendBuffers.Count; i++) { random.NextBytes(sendBuffers[i].Array); } client.SendAsync(clientEventArgs, sendBuffers, SocketFlags.None, sendHandler); }; } sendHandler(0); }); Assert.True(serverFinished.Task.Wait(TestTimeout)); Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); }
// "An invalid argument was supplied" public void Socket_EnableDualModeAfterV4Bind_Throws() { using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { serverSocket.DualMode = false; serverSocket.BindToAnonymousPort(IPAddress.IPv6Any); Assert.Throws<SocketException>(() => { serverSocket.DualMode = true; }); } }
public async Task SendToRecvFrom_Datagram_UDP(IPAddress loopbackAddress) { IPAddress leftAddress = loopbackAddress, rightAddress = loopbackAddress; // TODO #5185: Harden against packet loss const int DatagramSize = 256; const int DatagramsToSend = 256; const int AckTimeout = 1000; const int TestTimeout = 30000; var left = new Socket(leftAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); left.BindToAnonymousPort(leftAddress); var right = new Socket(rightAddress.AddressFamily, SocketType.Dgram, ProtocolType.Udp); right.BindToAnonymousPort(rightAddress); var leftEndpoint = (IPEndPoint)left.LocalEndPoint; var rightEndpoint = (IPEndPoint)right.LocalEndPoint; var receiverAck = new SemaphoreSlim(0); var senderAck = new SemaphoreSlim(0); var receivedChecksums = new uint?[DatagramsToSend]; Task leftThread = Task.Run(async() => { using (left) { EndPoint remote = leftEndpoint.Create(leftEndpoint.Serialize()); var recvBuffer = new byte[DatagramSize]; for (int i = 0; i < DatagramsToSend; i++) { SocketReceiveFromResult result = await ReceiveFromAsync( left, new ArraySegment <byte>(recvBuffer), remote); Assert.Equal(DatagramSize, result.ReceivedBytes); Assert.Equal(rightEndpoint, result.RemoteEndPoint); int datagramId = recvBuffer[0]; Assert.Null(receivedChecksums[datagramId]); receivedChecksums[datagramId] = Fletcher32.Checksum(recvBuffer, 0, result.ReceivedBytes); receiverAck.Release(); Assert.True(await senderAck.WaitAsync(TestTimeout)); } } }); var sentChecksums = new uint[DatagramsToSend]; using (right) { var random = new Random(); var sendBuffer = new byte[DatagramSize]; for (int i = 0; i < DatagramsToSend; i++) { random.NextBytes(sendBuffer); sendBuffer[0] = (byte)i; int sent = await SendToAsync(right, new ArraySegment <byte>(sendBuffer), leftEndpoint); Assert.True(await receiverAck.WaitAsync(AckTimeout)); senderAck.Release(); Assert.Equal(DatagramSize, sent); sentChecksums[i] = Fletcher32.Checksum(sendBuffer, 0, sent); } } await leftThread; for (int i = 0; i < DatagramsToSend; i++) { Assert.NotNull(receivedChecksums[i]); Assert.Equal(sentChecksums[i], (uint)receivedChecksums[i]); } }
private void DualModeConnect_BeginAccept_Helper(IPAddress listenOn, IPAddress connectTo) { using (Socket serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp)) { int port = serverSocket.BindToAnonymousPort(listenOn); serverSocket.Listen(1); IAsyncResult async = serverSocket.BeginAccept(null, null); SocketClient client = new SocketClient(_log, serverSocket, connectTo, port); // Due to the nondeterministic nature of calling dispose on a Socket that is doing // an EndAccept operation, we expect two types of exceptions to happen. Socket clientSocket; try { clientSocket = serverSocket.EndAccept(async); Assert.True(clientSocket.Connected); AssertDualModeEnabled(clientSocket, listenOn); Assert.Equal(AddressFamily.InterNetworkV6, clientSocket.AddressFamily); if (connectTo == IPAddress.Loopback) { Assert.Contains(((IPEndPoint)clientSocket.LocalEndPoint).Address, ValidIPv6Loopbacks); } else { Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address); } Assert.Equal(connectTo.MapToIPv6(), ((IPEndPoint)clientSocket.LocalEndPoint).Address); } catch (ObjectDisposedException) { } catch (SocketException) { } Assert.True( client.WaitHandle.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection"); if ( client.Error != SocketError.Success) { throw new SocketException((int)client.Error); } } }
public void SendRecvAsync_Stream_TCP(IPAddress listenAt, bool useMultipleBuffers) { const int BytesToSend = 123456; const int ListenBacklog = 1; const int LingerTime = 60; const int TestTimeout = 30000; var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp); server.BindToAnonymousPort(listenAt); server.Listen(ListenBacklog); var serverFinished = new TaskCompletionSource<bool>(); int bytesReceived = 0; var receivedChecksum = new Fletcher32(); var serverEventArgs = new SocketAsyncEventArgs(); server.AcceptAsync(serverEventArgs, remote => { Action<int> recvHandler = null; bool first = true; if (!useMultipleBuffers) { var recvBuffer = new byte[256]; recvHandler = received => { if (!first) { if (received == 0) { remote.Dispose(); server.Dispose(); serverFinished.SetResult(true); return; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } else { first = false; } remote.ReceiveAsync(serverEventArgs, recvBuffer, 0, recvBuffer.Length, SocketFlags.None, recvHandler); }; } else { var recvBuffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[123]), new ArraySegment<byte>(new byte[256], 2, 100), new ArraySegment<byte>(new byte[1], 0, 0), new ArraySegment<byte>(new byte[64], 9, 33) }; recvHandler = received => { if (!first) { if (received == 0) { remote.Dispose(); server.Dispose(); serverFinished.SetResult(true); return; } bytesReceived += received; for (int i = 0, remaining = received; i < recvBuffers.Count && remaining > 0; i++) { ArraySegment<byte> buffer = recvBuffers[i]; int toAdd = Math.Min(buffer.Count, remaining); receivedChecksum.Add(buffer.Array, buffer.Offset, toAdd); remaining -= toAdd; } } else { first = false; } remote.ReceiveAsync(serverEventArgs, recvBuffers, SocketFlags.None, recvHandler); }; } recvHandler(0); }); EndPoint clientEndpoint = server.LocalEndPoint; var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); int bytesSent = 0; var sentChecksum = new Fletcher32(); var clientEventArgs = new SocketAsyncEventArgs(); client.ConnectAsync(clientEventArgs, clientEndpoint, () => { Action<int> sendHandler = null; var random = new Random(); var remaining = BytesToSend; bool first = true; if (!useMultipleBuffers) { var sendBuffer = new byte[512]; sendHandler = sent => { if (!first) { bytesSent += sent; sentChecksum.Add(sendBuffer, 0, sent); remaining -= sent; Assert.True(remaining >= 0); if (remaining == 0) { client.LingerState = new LingerOption(true, LingerTime); client.Dispose(); return; } } else { first = false; } random.NextBytes(sendBuffer); client.SendAsync(clientEventArgs, sendBuffer, 0, Math.Min(sendBuffer.Length, remaining), SocketFlags.None, sendHandler); }; } else { var sendBuffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(new byte[23]), new ArraySegment<byte>(new byte[256], 2, 100), new ArraySegment<byte>(new byte[1], 0, 0), new ArraySegment<byte>(new byte[64], 9, 9) }; sendHandler = sent => { if (!first) { bytesSent += sent; for (int i = 0, r = sent; i < sendBuffers.Count && r > 0; i++) { ArraySegment<byte> buffer = sendBuffers[i]; int toAdd = Math.Min(buffer.Count, r); sentChecksum.Add(buffer.Array, buffer.Offset, toAdd); r -= toAdd; } remaining -= sent; if (remaining <= 0) { client.LingerState = new LingerOption(true, LingerTime); client.Dispose(); return; } } else { first = false; } for (int i = 0; i < sendBuffers.Count; i++) { random.NextBytes(sendBuffers[i].Array); } client.SendAsync(clientEventArgs, sendBuffers, SocketFlags.None, sendHandler); }; } sendHandler(0); }); Assert.True(serverFinished.Task.Wait(TestTimeout), "Completed within allowed time"); Assert.Equal(bytesSent, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); }
public void ReceiveSentMessages_ReuseEventArgs_Success(bool ipv4, int bufferMode) { const int DatagramsToSend = 5; const int TimeoutMs = 30_000; AddressFamily family; IPAddress loopback, any; SocketOptionLevel level; if (ipv4) { family = AddressFamily.InterNetwork; loopback = IPAddress.Loopback; any = IPAddress.Any; level = SocketOptionLevel.IP; } else { family = AddressFamily.InterNetworkV6; loopback = IPAddress.IPv6Loopback; any = IPAddress.IPv6Any; level = SocketOptionLevel.IPv6; } using var receiver = new Socket(family, SocketType.Dgram, ProtocolType.Udp); using var sender = new Socket(family, SocketType.Dgram, ProtocolType.Udp); using var saea = new SocketAsyncEventArgs(); var completed = new ManualResetEventSlim(); saea.Completed += delegate { completed.Set(); }; int port = receiver.BindToAnonymousPort(loopback); receiver.SetSocketOption(level, SocketOptionName.PacketInformation, true); sender.Bind(new IPEndPoint(loopback, 0)); saea.RemoteEndPoint = new IPEndPoint(any, 0); Random random = new Random(0); byte[] sendBuffer = new byte[1024]; random.NextBytes(sendBuffer); for (int i = 0; i < DatagramsToSend; i++) { byte[] receiveBuffer = new byte[1024]; switch (bufferMode) { case 0: // single buffer saea.SetBuffer(receiveBuffer, 0, 1024); break; case 1: // single buffer in buffer list saea.BufferList = new List <ArraySegment <byte> > { new ArraySegment <byte>(receiveBuffer) }; break; case 2: // multiple buffers in buffer list saea.BufferList = new List <ArraySegment <byte> > { new ArraySegment <byte>(receiveBuffer, 0, 512), new ArraySegment <byte>(receiveBuffer, 512, 512) }; break; } bool pending = receiver.ReceiveMessageFromAsync(saea); sender.SendTo(sendBuffer, new IPEndPoint(loopback, port)); if (pending) { Assert.True(completed.Wait(TimeoutMs), "Expected operation to complete within timeout"); } completed.Reset(); Assert.Equal(1024, saea.BytesTransferred); AssertExtensions.SequenceEqual(sendBuffer, receiveBuffer); Assert.Equal(sender.LocalEndPoint, saea.RemoteEndPoint); Assert.Equal(((IPEndPoint)sender.LocalEndPoint).Address, saea.ReceiveMessageFromPacketInfo.Address); } }
public void SendFile_Synchronous(IPAddress listenAt, bool sendPreAndPostBuffers, int bytesToSend, bool forceNonBlocking) { const int ListenBacklog = 1; const int TestTimeout = 30000; // Create file to send byte[] preBuffer; byte[] postBuffer; Fletcher32 sentChecksum; string filename = CreateFileToSend(bytesToSend, sendPreAndPostBuffers, out preBuffer, out postBuffer, out sentChecksum); // Start server var server = new Socket(listenAt.AddressFamily, SocketType.Stream, ProtocolType.Tcp); server.BindToAnonymousPort(listenAt); server.Listen(ListenBacklog); server.ForceNonBlocking(forceNonBlocking); int bytesReceived = 0; var receivedChecksum = new Fletcher32(); var serverThread = new Thread(() => { using (server) { Socket remote = server.Accept(); Assert.NotNull(remote); remote.ForceNonBlocking(forceNonBlocking); using (remote) { var recvBuffer = new byte[256]; for (; ;) { int received = remote.Receive(recvBuffer, 0, recvBuffer.Length, SocketFlags.None); if (received == 0) { break; } bytesReceived += received; receivedChecksum.Add(recvBuffer, 0, received); } } } }); serverThread.Start(); // Run client EndPoint clientEndpoint = server.LocalEndPoint; var client = new Socket(clientEndpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); client.ForceNonBlocking(forceNonBlocking); client.Connect(clientEndpoint); using (client) { client.SendFile(filename, preBuffer, postBuffer, TransmitFileOptions.UseDefaultWorkerThread); client.Shutdown(SocketShutdown.Send); } Assert.True(serverThread.Join(TestTimeout), "Completed within allowed time"); Assert.Equal(bytesToSend, bytesReceived); Assert.Equal(sentChecksum.Sum, receivedChecksum.Sum); // Clean up the file we created File.Delete(filename); }