|
| 1 | +/// @file |
| 2 | +/// @copyright Copyright (c) 2026 SafeTwice S.L. All rights reserved. |
| 3 | +/// @license See LICENSE.txt |
| 4 | + |
| 5 | +using System; |
| 6 | +using System.Net; |
| 7 | +using System.Net.Sockets; |
| 8 | +using System.Threading; |
| 9 | + |
| 10 | +namespace Utilities.DotNet.Network |
| 11 | +{ |
| 12 | + /// <summary> |
| 13 | + /// Utility class providing extension methods for the <see cref="Socket"/> class. |
| 14 | + /// </summary> |
| 15 | + public static class SocketExtensions |
| 16 | + { |
| 17 | + //=========================================================================== |
| 18 | + // PUBLIC METHODS |
| 19 | + //=========================================================================== |
| 20 | + |
| 21 | + /// <summary> |
| 22 | + /// Established a connection to a remote host. |
| 23 | + /// </summary> |
| 24 | + /// <param name="socket">Socket used to establish connection.</param> |
| 25 | + /// <param name="address">The IPAddress of the remote host to connect to.</param> |
| 26 | + /// <param name="port">The port on the remote host to connect to.</param> |
| 27 | + /// <param name="timeout">The number of milliseconds to wait for connection to be established, |
| 28 | + /// or <see cref="Timeout.Infinite"/> to wait indefinitely.</param> |
| 29 | + /// <exception cref="SocketException">An error occurred when accessing the socket.</exception> |
| 30 | + /// <exception cref="System.ObjectDisposedException">The <see cref="Socket"/> has been disposed.</exception> |
| 31 | + /// <exception cref="System.Security.SecurityException">A caller higher in the call stack does not have permission for the requested operation.</exception> |
| 32 | + /// <exception cref="System.InvalidOperationException">The <see cref="Socket"/> has been placed in a listening state by calling <see cref="Socket.Listen(int)"/>.</exception> |
| 33 | + public static void Connect( this Socket socket, IPAddress address, int port, int timeout ) |
| 34 | + { |
| 35 | + if( timeout == Timeout.Infinite ) |
| 36 | + { |
| 37 | + socket.Connect( address, port ); |
| 38 | + } |
| 39 | + else |
| 40 | + { |
| 41 | + var connectTask = socket.ConnectAsync( address, port ); |
| 42 | + |
| 43 | + try |
| 44 | + { |
| 45 | + if( !connectTask.Wait( timeout ) ) |
| 46 | + { |
| 47 | + socket.Close(); |
| 48 | + throw new SocketException( (int) SocketError.TimedOut ); |
| 49 | + } |
| 50 | + } |
| 51 | + catch( AggregateException ex ) |
| 52 | + { |
| 53 | + socket.Close(); |
| 54 | + throw ex.InnerException ?? ex; |
| 55 | + } |
| 56 | + |
| 57 | + if( connectTask.IsFaulted ) |
| 58 | + { |
| 59 | + socket.Close(); |
| 60 | + throw connectTask.Exception?.InnerException ?? connectTask.Exception!; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
0 commit comments