mscorlib(4.0.0.0) API with additions
Socket.cs
1 using System.Collections;
4 using System.IO;
8 using System.Security;
10 using System.Threading;
11 using System.Threading.Tasks;
12 
13 namespace System.Net.Sockets
14 {
16  public class Socket : IDisposable
17  {
18  private class CacheSet
19  {
20  internal CallbackClosure ConnectClosureCache;
21 
22  internal CallbackClosure AcceptClosureCache;
23 
24  internal CallbackClosure SendClosureCache;
25 
26  internal CallbackClosure ReceiveClosureCache;
27 
28  internal OverlappedCache SendOverlappedCache;
29 
30  internal OverlappedCache ReceiveOverlappedCache;
31  }
32 
33  private class MultipleAddressConnectAsyncResult : ContextAwareResult
34  {
35  internal Socket socket;
36 
37  internal IPAddress[] addresses;
38 
39  internal int index;
40 
41  internal int port;
42 
43  internal Exception lastException;
44 
45  internal EndPoint RemoteEndPoint
46  {
47  get
48  {
49  if (addresses != null && index > 0 && index < addresses.Length)
50  {
51  return new IPEndPoint(addresses[index], port);
52  }
53  return null;
54  }
55  }
56 
57  internal MultipleAddressConnectAsyncResult(IPAddress[] addresses, int port, Socket socket, object myState, AsyncCallback myCallBack)
58  : base(socket, myState, myCallBack)
59  {
60  this.addresses = addresses;
61  this.port = port;
62  this.socket = socket;
63  }
64  }
65 
66  private class StateTaskCompletionSource<TField1, TResult> : TaskCompletionSource<TResult>
67  {
68  internal TField1 _field1;
69 
70  public StateTaskCompletionSource(object baseState)
71  : base(baseState)
72  {
73  }
74  }
75 
76  private class StateTaskCompletionSource<TField1, TField2, TResult> : StateTaskCompletionSource<TField1, TResult>
77  {
78  internal TField2 _field2;
79 
80  public StateTaskCompletionSource(object baseState)
81  : base(baseState)
82  {
83  }
84  }
85 
86  private sealed class CachedTaskEventArgs
87  {
88  public TaskSocketAsyncEventArgs<Socket> Accept;
89 
90  public Int32TaskSocketAsyncEventArgs Receive;
91 
92  public Int32TaskSocketAsyncEventArgs Send;
93  }
94 
95  private class TaskSocketAsyncEventArgs<TResult> : SocketAsyncEventArgs
96  {
97  internal AsyncTaskMethodBuilder<TResult> _builder;
98 
99  internal bool _accessed;
100 
101  internal AsyncTaskMethodBuilder<TResult> GetCompletionResponsibility(out bool responsibleForReturningToPool)
102  {
103  lock (this)
104  {
105  responsibleForReturningToPool = _accessed;
106  _accessed = true;
107  Task<TResult> task = _builder.Task;
108  return _builder;
109  }
110  }
111  }
112 
113  private sealed class Int32TaskSocketAsyncEventArgs : TaskSocketAsyncEventArgs<int>
114  {
115  internal Task<int> _successfullyCompletedTask;
116 
117  internal bool _wrapExceptionsInIOExceptions;
118  }
119 
120  internal const int DefaultCloseTimeout = -1;
121 
122  private object m_AcceptQueueOrConnectResult;
123 
124  private SafeCloseSocket m_Handle;
125 
126  internal EndPoint m_RightEndPoint;
127 
128  internal EndPoint m_RemoteEndPoint;
129 
130  private bool m_IsConnected;
131 
132  private bool m_IsDisconnected;
133 
134  private bool willBlock = true;
135 
136  private bool willBlockInternal = true;
137 
138  private bool isListening;
139 
140  private bool m_NonBlockingConnectInProgress;
141 
142  private EndPoint m_NonBlockingConnectRightEndPoint;
143 
144  private AddressFamily addressFamily;
145 
146  private SocketType socketType;
147 
148  private ProtocolType protocolType;
149 
150  private CacheSet m_Caches;
151 
152  internal static volatile bool UseOverlappedIO;
153 
154  private bool useOverlappedIO;
155 
156  private bool m_BoundToThreadPool;
157 
158  private bool m_ReceivingPacketInformation;
159 
160  private ManualResetEvent m_AsyncEvent;
161 
162  private RegisteredWaitHandle m_RegisteredWait;
163 
164  private AsyncEventBits m_BlockEventBits;
165 
166  private SocketAddress m_PermittedRemoteAddress;
167 
168  private DynamicWinsockMethods m_DynamicWinsockMethods;
169 
170  private static object s_InternalSyncObject;
171 
172  private int m_CloseTimeout = -1;
173 
174  private int m_IntCleanedUp;
175 
176  private const int microcnv = 1000000;
177 
178  private static readonly int protocolInformationSize = Marshal.SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.WSAPROTOCOL_INFO));
179 
180  internal static volatile bool s_SupportsIPv4;
181 
182  internal static volatile bool s_SupportsIPv6;
183 
184  internal static volatile bool s_OSSupportsIPv6;
185 
186  internal static volatile bool s_Initialized;
187 
188  private static volatile WaitOrTimerCallback s_RegisteredWaitCallback;
189 
190  private static volatile bool s_LoggingEnabled;
191 
192  internal static volatile bool s_PerfCountersEnabled;
193 
194  private static readonly EventHandler<SocketAsyncEventArgs> AcceptCompletedHandler = delegate(object s, SocketAsyncEventArgs e)
195  {
196  CompleteAccept((Socket)s, (TaskSocketAsyncEventArgs<Socket>)e);
197  };
198 
199  private static readonly EventHandler<SocketAsyncEventArgs> ReceiveCompletedHandler = delegate(object s, SocketAsyncEventArgs e)
200  {
201  CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: true);
202  };
203 
204  private static readonly EventHandler<SocketAsyncEventArgs> SendCompletedHandler = delegate(object s, SocketAsyncEventArgs e)
205  {
206  CompleteSendReceive((Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive: false);
207  };
208 
209  private static readonly TaskSocketAsyncEventArgs<Socket> s_rentedSocketSentinel = new TaskSocketAsyncEventArgs<Socket>();
210 
211  private static readonly Int32TaskSocketAsyncEventArgs s_rentedInt32Sentinel = new Int32TaskSocketAsyncEventArgs();
212 
213  private static readonly Task<int> s_zeroTask = Task.FromResult(0);
214 
215  private CachedTaskEventArgs _cachedTaskEventArgs;
216 
220  [Obsolete("SupportsIPv4 is obsoleted for this type, please use OSSupportsIPv4 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
221  public static bool SupportsIPv4
222  {
223  get
224  {
225  InitializeSockets();
226  return s_SupportsIPv4;
227  }
228  }
229 
233  public static bool OSSupportsIPv4
234  {
235  get
236  {
237  InitializeSockets();
238  return s_SupportsIPv4;
239  }
240  }
241 
245  [Obsolete("SupportsIPv6 is obsoleted for this type, please use OSSupportsIPv6 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
246  public static bool SupportsIPv6
247  {
248  get
249  {
250  InitializeSockets();
251  return s_SupportsIPv6;
252  }
253  }
254 
255  internal static bool LegacySupportsIPv6
256  {
257  get
258  {
259  InitializeSockets();
260  return s_SupportsIPv6;
261  }
262  }
263 
267  public static bool OSSupportsIPv6
268  {
269  get
270  {
271  InitializeSockets();
272  return s_OSSupportsIPv6;
273  }
274  }
275 
280  public int Available
281  {
282  get
283  {
284  if (CleanedUp)
285  {
286  throw new ObjectDisposedException(GetType().FullName);
287  }
288  int argp = 0;
289  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.ioctlsocket(m_Handle, 1074030207, ref argp);
290  if (socketError == SocketError.SocketError)
291  {
292  SocketException ex = new SocketException();
293  UpdateStatusAfterSocketError(ex);
294  if (s_LoggingEnabled)
295  {
296  Logging.Exception(Logging.Sockets, this, "Available", ex);
297  }
298  throw ex;
299  }
300  return argp;
301  }
302  }
303 
308  public EndPoint LocalEndPoint
309  {
310  get
311  {
312  if (CleanedUp)
313  {
314  throw new ObjectDisposedException(GetType().FullName);
315  }
316  if (m_NonBlockingConnectInProgress && Poll(0, SelectMode.SelectWrite))
317  {
318  m_IsConnected = true;
319  m_RightEndPoint = m_NonBlockingConnectRightEndPoint;
320  m_NonBlockingConnectInProgress = false;
321  }
322  if (m_RightEndPoint == null)
323  {
324  return null;
325  }
326  SocketAddress socketAddress = m_RightEndPoint.Serialize();
327  if (UnsafeNclNativeMethods.OSSOCK.getsockname(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size) != 0)
328  {
329  SocketException ex = new SocketException();
330  UpdateStatusAfterSocketError(ex);
331  if (s_LoggingEnabled)
332  {
333  Logging.Exception(Logging.Sockets, this, "LocalEndPoint", ex);
334  }
335  throw ex;
336  }
337  return m_RightEndPoint.Create(socketAddress);
338  }
339  }
340 
345  public EndPoint RemoteEndPoint
346  {
347  get
348  {
349  if (CleanedUp)
350  {
351  throw new ObjectDisposedException(GetType().FullName);
352  }
353  if (m_RemoteEndPoint == null)
354  {
355  if (m_NonBlockingConnectInProgress && Poll(0, SelectMode.SelectWrite))
356  {
357  m_IsConnected = true;
358  m_RightEndPoint = m_NonBlockingConnectRightEndPoint;
359  m_NonBlockingConnectInProgress = false;
360  }
361  if (m_RightEndPoint == null)
362  {
363  return null;
364  }
365  SocketAddress socketAddress = m_RightEndPoint.Serialize();
366  if (UnsafeNclNativeMethods.OSSOCK.getpeername(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size) != 0)
367  {
368  SocketException ex = new SocketException();
369  UpdateStatusAfterSocketError(ex);
370  if (s_LoggingEnabled)
371  {
372  Logging.Exception(Logging.Sockets, this, "RemoteEndPoint", ex);
373  }
374  throw ex;
375  }
376  try
377  {
378  m_RemoteEndPoint = m_RightEndPoint.Create(socketAddress);
379  }
380  catch
381  {
382  }
383  }
384  return m_RemoteEndPoint;
385  }
386  }
387 
390  public IntPtr Handle
391  {
392  get
393  {
394  ExceptionHelper.UnmanagedPermission.Demand();
395  return m_Handle.DangerousGetHandle();
396  }
397  }
398 
399  internal SafeCloseSocket SafeHandle => m_Handle;
400 
406  public bool Blocking
407  {
408  get
409  {
410  return willBlock;
411  }
412  set
413  {
414  if (CleanedUp)
415  {
416  throw new ObjectDisposedException(GetType().FullName);
417  }
418  bool current;
419  SocketError socketError = InternalSetBlocking(value, out current);
420  if (socketError != 0)
421  {
422  SocketException ex = new SocketException(socketError);
423  UpdateStatusAfterSocketError(ex);
424  if (s_LoggingEnabled)
425  {
426  Logging.Exception(Logging.Sockets, this, "Blocking", ex);
427  }
428  throw ex;
429  }
430  willBlock = current;
431  }
432  }
433 
438  public bool UseOnlyOverlappedIO
439  {
440  get
441  {
442  return useOverlappedIO;
443  }
444  set
445  {
446  if (m_BoundToThreadPool)
447  {
448  throw new InvalidOperationException(SR.GetString("net_io_completionportwasbound"));
449  }
450  useOverlappedIO = value;
451  }
452  }
453 
457  public bool Connected
458  {
459  get
460  {
461  if (m_NonBlockingConnectInProgress && Poll(0, SelectMode.SelectWrite))
462  {
463  m_IsConnected = true;
464  m_RightEndPoint = m_NonBlockingConnectRightEndPoint;
465  m_NonBlockingConnectInProgress = false;
466  }
467  return m_IsConnected;
468  }
469  }
470 
473  public AddressFamily AddressFamily => addressFamily;
474 
477  public SocketType SocketType => socketType;
478 
481  public ProtocolType ProtocolType => protocolType;
482 
486  public bool IsBound => m_RightEndPoint != null;
487 
495  public bool ExclusiveAddressUse
496  {
497  get
498  {
499  if ((int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse) == 0)
500  {
501  return false;
502  }
503  return true;
504  }
505  set
506  {
507  if (IsBound)
508  {
509  throw new InvalidOperationException(SR.GetString("net_sockets_mustnotbebound"));
510  }
511  SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, value ? 1 : 0);
512  }
513  }
514 
520  public int ReceiveBufferSize
521  {
522  get
523  {
524  return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer);
525  }
526  set
527  {
528  if (value < 0)
529  {
530  throw new ArgumentOutOfRangeException("value");
531  }
532  SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
533  }
534  }
535 
541  public int SendBufferSize
542  {
543  get
544  {
545  return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer);
546  }
547  set
548  {
549  if (value < 0)
550  {
551  throw new ArgumentOutOfRangeException("value");
552  }
553  SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, value);
554  }
555  }
556 
562  public int ReceiveTimeout
563  {
564  get
565  {
566  return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout);
567  }
568  set
569  {
570  if (value < -1)
571  {
572  throw new ArgumentOutOfRangeException("value");
573  }
574  if (value == -1)
575  {
576  value = 0;
577  }
578  SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, value);
579  }
580  }
581 
587  public int SendTimeout
588  {
589  get
590  {
591  return (int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout);
592  }
593  set
594  {
595  if (value < -1)
596  {
597  throw new ArgumentOutOfRangeException("value");
598  }
599  if (value == -1)
600  {
601  value = 0;
602  }
603  SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, value);
604  }
605  }
606 
612  {
613  get
614  {
616  }
617  set
618  {
619  SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, value);
620  }
621  }
622 
628  public bool NoDelay
629  {
630  get
631  {
632  if ((int)GetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Debug) == 0)
633  {
634  return false;
635  }
636  return true;
637  }
638  set
639  {
640  SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.Debug, value ? 1 : 0);
641  }
642  }
643 
650  public short Ttl
651  {
652  get
653  {
654  if (addressFamily == AddressFamily.InterNetwork)
655  {
656  return (short)(int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress);
657  }
658  if (addressFamily == AddressFamily.InterNetworkV6)
659  {
660  return (short)(int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.ReuseAddress);
661  }
662  throw new NotSupportedException(SR.GetString("net_invalidversion"));
663  }
664  set
665  {
666  if (value < 0 || value > 255)
667  {
668  throw new ArgumentOutOfRangeException("value");
669  }
670  if (addressFamily == AddressFamily.InterNetwork)
671  {
672  SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, value);
673  return;
674  }
675  if (addressFamily == AddressFamily.InterNetworkV6)
676  {
677  SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.ReuseAddress, value);
678  return;
679  }
680  throw new NotSupportedException(SR.GetString("net_invalidversion"));
681  }
682  }
683 
690  public bool DontFragment
691  {
692  get
693  {
694  if (addressFamily == AddressFamily.InterNetwork)
695  {
696  if ((int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment) == 0)
697  {
698  return false;
699  }
700  return true;
701  }
702  throw new NotSupportedException(SR.GetString("net_invalidversion"));
703  }
704  set
705  {
706  if (addressFamily == AddressFamily.InterNetwork)
707  {
708  SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DontFragment, value ? 1 : 0);
709  return;
710  }
711  throw new NotSupportedException(SR.GetString("net_invalidversion"));
712  }
713  }
714 
720  public bool MulticastLoopback
721  {
722  get
723  {
724  if (addressFamily == AddressFamily.InterNetwork)
725  {
726  if ((int)GetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback) == 0)
727  {
728  return false;
729  }
730  return true;
731  }
732  if (addressFamily == AddressFamily.InterNetworkV6)
733  {
734  if ((int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback) == 0)
735  {
736  return false;
737  }
738  return true;
739  }
740  throw new NotSupportedException(SR.GetString("net_invalidversion"));
741  }
742  set
743  {
744  if (addressFamily == AddressFamily.InterNetwork)
745  {
746  SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, value ? 1 : 0);
747  return;
748  }
749  if (addressFamily == AddressFamily.InterNetworkV6)
750  {
751  SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback, value ? 1 : 0);
752  return;
753  }
754  throw new NotSupportedException(SR.GetString("net_invalidversion"));
755  }
756  }
757 
763  public bool EnableBroadcast
764  {
765  get
766  {
767  if ((int)GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast) == 0)
768  {
769  return false;
770  }
771  return true;
772  }
773  set
774  {
775  SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, value ? 1 : 0);
776  }
777  }
778 
782  public bool DualMode
783  {
784  get
785  {
786  if (AddressFamily != AddressFamily.InterNetworkV6)
787  {
788  throw new NotSupportedException(SR.GetString("net_invalidversion"));
789  }
790  return (int)GetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only) == 0;
791  }
792  set
793  {
794  if (AddressFamily != AddressFamily.InterNetworkV6)
795  {
796  throw new NotSupportedException(SR.GetString("net_invalidversion"));
797  }
798  SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, (!value) ? 1 : 0);
799  }
800  }
801 
802  private bool IsDualMode
803  {
804  get
805  {
806  if (AddressFamily == AddressFamily.InterNetworkV6)
807  {
808  return DualMode;
809  }
810  return false;
811  }
812  }
813 
814  private bool CanUseAcceptEx
815  {
816  get
817  {
818  if (!Thread.CurrentThread.IsThreadPoolThread && !SettingsSectionInternal.Section.AlwaysUseCompletionPortsForAccept)
819  {
820  return m_IsDisconnected;
821  }
822  return true;
823  }
824  }
825 
826  private static object InternalSyncObject
827  {
828  get
829  {
830  if (s_InternalSyncObject == null)
831  {
832  object value = new object();
833  Interlocked.CompareExchange(ref s_InternalSyncObject, value, null);
834  }
835  return s_InternalSyncObject;
836  }
837  }
838 
839  private CacheSet Caches
840  {
841  get
842  {
843  if (m_Caches == null)
844  {
845  m_Caches = new CacheSet();
846  }
847  return m_Caches;
848  }
849  }
850 
851  internal bool CleanedUp => m_IntCleanedUp == 1;
852 
853  internal TransportType Transport
854  {
855  get
856  {
857  if (protocolType != ProtocolType.Tcp)
858  {
859  if (protocolType != ProtocolType.Udp)
860  {
861  return TransportType.All;
862  }
863  return TransportType.Udp;
864  }
865  return TransportType.Tcp;
866  }
867  }
868 
873  public Socket(SocketType socketType, ProtocolType protocolType)
874  : this(AddressFamily.InterNetworkV6, socketType, protocolType)
875  {
876  DualMode = true;
877  }
878 
884  public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
885  {
886  s_LoggingEnabled = Logging.On;
887  if (s_LoggingEnabled)
888  {
889  Logging.Enter(Logging.Sockets, this, "Socket", addressFamily);
890  }
891  InitializeSockets();
892  m_Handle = SafeCloseSocket.CreateWSASocket(addressFamily, socketType, protocolType);
893  if (m_Handle.IsInvalid)
894  {
895  throw new SocketException();
896  }
897  this.addressFamily = addressFamily;
898  this.socketType = socketType;
899  this.protocolType = protocolType;
900  IPProtectionLevel iPProtectionLevel = SettingsSectionInternal.Section.IPProtectionLevel;
901  if (iPProtectionLevel != IPProtectionLevel.Unspecified)
902  {
903  SetIPProtectionLevel(iPProtectionLevel);
904  }
905  if (s_LoggingEnabled)
906  {
907  Logging.Exit(Logging.Sockets, this, "Socket", null);
908  }
909  }
910 
913  public unsafe Socket(SocketInformation socketInformation)
914  {
915  s_LoggingEnabled = Logging.On;
916  if (s_LoggingEnabled)
917  {
918  Logging.Enter(Logging.Sockets, this, "Socket", addressFamily);
919  }
920  ExceptionHelper.UnrestrictedSocketPermission.Demand();
921  InitializeSockets();
922  if (socketInformation.ProtocolInformation == null || socketInformation.ProtocolInformation.Length < protocolInformationSize)
923  {
924  throw new ArgumentException(SR.GetString("net_sockets_invalid_socketinformation"), "socketInformation.ProtocolInformation");
925  }
926  byte[] protocolInformation = socketInformation.ProtocolInformation;
927  fixed (byte* ptr = protocolInformation)
928  {
929  m_Handle = SafeCloseSocket.CreateWSASocket(ptr);
930  UnsafeNclNativeMethods.OSSOCK.WSAPROTOCOL_INFO wSAPROTOCOL_INFO = (UnsafeNclNativeMethods.OSSOCK.WSAPROTOCOL_INFO)Marshal.PtrToStructure((IntPtr)(void*)ptr, typeof(UnsafeNclNativeMethods.OSSOCK.WSAPROTOCOL_INFO));
931  addressFamily = wSAPROTOCOL_INFO.iAddressFamily;
932  socketType = (SocketType)wSAPROTOCOL_INFO.iSocketType;
933  protocolType = (ProtocolType)wSAPROTOCOL_INFO.iProtocol;
934  }
935  if (m_Handle.IsInvalid)
936  {
937  SocketException ex = new SocketException();
938  if (ex.ErrorCode == 10022)
939  {
940  throw new ArgumentException(SR.GetString("net_sockets_invalid_socketinformation"), "socketInformation");
941  }
942  throw ex;
943  }
944  if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6)
945  {
946  throw new NotSupportedException(SR.GetString("net_invalidversion"));
947  }
948  m_IsConnected = socketInformation.IsConnected;
949  willBlock = !socketInformation.IsNonBlocking;
950  InternalSetBlocking(willBlock);
951  isListening = socketInformation.IsListening;
952  UseOnlyOverlappedIO = socketInformation.UseOnlyOverlappedIO;
953  if (socketInformation.RemoteEndPoint != null)
954  {
955  m_RightEndPoint = socketInformation.RemoteEndPoint;
956  m_RemoteEndPoint = socketInformation.RemoteEndPoint;
957  }
958  else
959  {
960  EndPoint endPoint = null;
961  if (addressFamily == AddressFamily.InterNetwork)
962  {
963  endPoint = IPEndPoint.Any;
964  }
965  else if (addressFamily == AddressFamily.InterNetworkV6)
966  {
967  endPoint = IPEndPoint.IPv6Any;
968  }
969  SocketAddress socketAddress = endPoint.Serialize();
970  SocketError socketError;
971  try
972  {
973  socketError = UnsafeNclNativeMethods.OSSOCK.getsockname(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size);
974  }
976  {
977  socketError = SocketError.NotSocket;
978  }
979  if (socketError == SocketError.Success)
980  {
981  try
982  {
983  m_RightEndPoint = endPoint.Create(socketAddress);
984  }
985  catch
986  {
987  }
988  }
989  }
990  if (s_LoggingEnabled)
991  {
992  Logging.Exit(Logging.Sockets, this, "Socket", null);
993  }
994  }
995 
996  private Socket(SafeCloseSocket fd)
997  {
998  s_LoggingEnabled = Logging.On;
999  if (s_LoggingEnabled)
1000  {
1001  Logging.Enter(Logging.Sockets, this, "Socket", null);
1002  }
1003  InitializeSockets();
1004  if (fd == null || fd.IsInvalid)
1005  {
1006  throw new ArgumentException(SR.GetString("net_InvalidSocketHandle"));
1007  }
1008  m_Handle = fd;
1009  addressFamily = AddressFamily.Unknown;
1010  socketType = SocketType.Unknown;
1011  protocolType = ProtocolType.Unknown;
1012  if (s_LoggingEnabled)
1013  {
1014  Logging.Exit(Logging.Sockets, this, "Socket", null);
1015  }
1016  }
1017 
1018  internal bool CanTryAddressFamily(AddressFamily family)
1019  {
1020  if (family != addressFamily)
1021  {
1022  if (family == AddressFamily.InterNetwork)
1023  {
1024  return IsDualMode;
1025  }
1026  return false;
1027  }
1028  return true;
1029  }
1030 
1038  public void Bind(EndPoint localEP)
1039  {
1040  if (s_LoggingEnabled)
1041  {
1042  Logging.Enter(Logging.Sockets, this, "Bind", localEP);
1043  }
1044  if (CleanedUp)
1045  {
1046  throw new ObjectDisposedException(GetType().FullName);
1047  }
1048  if (localEP == null)
1049  {
1050  throw new ArgumentNullException("localEP");
1051  }
1052  EndPoint endPoint = localEP;
1053  IPEndPoint iPEndPoint = localEP as IPEndPoint;
1054  if (iPEndPoint != null)
1055  {
1056  iPEndPoint = iPEndPoint.Snapshot();
1057  endPoint = RemapIPEndPoint(iPEndPoint);
1058  SocketPermission socketPermission = new SocketPermission(NetworkAccess.Accept, Transport, iPEndPoint.Address.ToString(), iPEndPoint.Port);
1059  socketPermission.Demand();
1060  }
1061  else
1062  {
1063  ExceptionHelper.UnmanagedPermission.Demand();
1064  }
1065  SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(endPoint);
1066  DoBind(endPoint, socketAddress);
1067  if (s_LoggingEnabled)
1068  {
1069  Logging.Exit(Logging.Sockets, this, "Bind", "");
1070  }
1071  }
1072 
1073  internal void InternalBind(EndPoint localEP)
1074  {
1075  if (s_LoggingEnabled)
1076  {
1077  Logging.Enter(Logging.Sockets, this, "InternalBind", localEP);
1078  }
1079  if (CleanedUp)
1080  {
1081  throw new ObjectDisposedException(GetType().FullName);
1082  }
1083  EndPoint remoteEP = localEP;
1084  SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP);
1085  DoBind(remoteEP, socketAddress);
1086  if (s_LoggingEnabled)
1087  {
1088  Logging.Exit(Logging.Sockets, this, "InternalBind", "");
1089  }
1090  }
1091 
1092  private void DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
1093  {
1094  IPEndPoint iPEndPoint = endPointSnapshot as IPEndPoint;
1095  if (!OSSupportsIPv4 && iPEndPoint != null && iPEndPoint.Address.IsIPv4MappedToIPv6)
1096  {
1097  SocketException ex = new SocketException(SocketError.InvalidArgument);
1098  UpdateStatusAfterSocketError(ex);
1099  if (s_LoggingEnabled)
1100  {
1101  Logging.Exception(Logging.Sockets, this, "DoBind", ex);
1102  }
1103  throw ex;
1104  }
1105  if (UnsafeNclNativeMethods.OSSOCK.bind(m_Handle, socketAddress.m_Buffer, socketAddress.m_Size) != 0)
1106  {
1107  SocketException ex2 = new SocketException();
1108  UpdateStatusAfterSocketError(ex2);
1109  if (s_LoggingEnabled)
1110  {
1111  Logging.Exception(Logging.Sockets, this, "DoBind", ex2);
1112  }
1113  throw ex2;
1114  }
1115  if (m_RightEndPoint == null)
1116  {
1117  m_RightEndPoint = endPointSnapshot;
1118  }
1119  }
1120 
1129  public void Connect(EndPoint remoteEP)
1130  {
1131  if (CleanedUp)
1132  {
1133  throw new ObjectDisposedException(GetType().FullName);
1134  }
1135  if (remoteEP == null)
1136  {
1137  throw new ArgumentNullException("remoteEP");
1138  }
1139  if (m_IsDisconnected)
1140  {
1141  throw new InvalidOperationException(SR.GetString("net_sockets_disconnectedConnect"));
1142  }
1143  if (isListening)
1144  {
1145  throw new InvalidOperationException(SR.GetString("net_sockets_mustnotlisten"));
1146  }
1147  ValidateBlockingMode();
1148  DnsEndPoint dnsEndPoint = remoteEP as DnsEndPoint;
1149  if (dnsEndPoint != null)
1150  {
1151  if (dnsEndPoint.AddressFamily != 0 && !CanTryAddressFamily(dnsEndPoint.AddressFamily))
1152  {
1153  throw new NotSupportedException(SR.GetString("net_invalidversion"));
1154  }
1155  Connect(dnsEndPoint.Host, dnsEndPoint.Port);
1156  return;
1157  }
1158  EndPoint remoteEP2 = remoteEP;
1159  SocketAddress socketAddress = CheckCacheRemote(ref remoteEP2, isOverwrite: true);
1160  if (!Blocking)
1161  {
1162  m_NonBlockingConnectRightEndPoint = remoteEP2;
1163  m_NonBlockingConnectInProgress = true;
1164  }
1165  DoConnect(remoteEP2, socketAddress);
1166  }
1167 
1179  public void Connect(IPAddress address, int port)
1180  {
1181  if (s_LoggingEnabled)
1182  {
1183  Logging.Enter(Logging.Sockets, this, "Connect", address);
1184  }
1185  if (CleanedUp)
1186  {
1187  throw new ObjectDisposedException(GetType().FullName);
1188  }
1189  if (address == null)
1190  {
1191  throw new ArgumentNullException("address");
1192  }
1193  if (!ValidationHelper.ValidateTcpPort(port))
1194  {
1195  throw new ArgumentOutOfRangeException("port");
1196  }
1197  if (!CanTryAddressFamily(address.AddressFamily))
1198  {
1199  throw new NotSupportedException(SR.GetString("net_invalidversion"));
1200  }
1201  IPEndPoint remoteEP = new IPEndPoint(address, port);
1202  Connect(remoteEP);
1203  if (s_LoggingEnabled)
1204  {
1205  Logging.Exit(Logging.Sockets, this, "Connect", null);
1206  }
1207  }
1208 
1219  public void Connect(string host, int port)
1220  {
1221  if (s_LoggingEnabled)
1222  {
1223  Logging.Enter(Logging.Sockets, this, "Connect", host);
1224  }
1225  if (CleanedUp)
1226  {
1227  throw new ObjectDisposedException(GetType().FullName);
1228  }
1229  if (host == null)
1230  {
1231  throw new ArgumentNullException("host");
1232  }
1233  if (!ValidationHelper.ValidateTcpPort(port))
1234  {
1235  throw new ArgumentOutOfRangeException("port");
1236  }
1237  if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6)
1238  {
1239  throw new NotSupportedException(SR.GetString("net_invalidversion"));
1240  }
1241  IPAddress[] hostAddresses = Dns.GetHostAddresses(host);
1242  Connect(hostAddresses, port);
1243  if (s_LoggingEnabled)
1244  {
1245  Logging.Exit(Logging.Sockets, this, "Connect", null);
1246  }
1247  }
1248 
1260  public void Connect(IPAddress[] addresses, int port)
1261  {
1262  if (s_LoggingEnabled)
1263  {
1264  Logging.Enter(Logging.Sockets, this, "Connect", addresses);
1265  }
1266  if (CleanedUp)
1267  {
1268  throw new ObjectDisposedException(GetType().FullName);
1269  }
1270  if (addresses == null)
1271  {
1272  throw new ArgumentNullException("addresses");
1273  }
1274  if (addresses.Length == 0)
1275  {
1276  throw new ArgumentException(SR.GetString("net_sockets_invalid_ipaddress_length"), "addresses");
1277  }
1278  if (!ValidationHelper.ValidateTcpPort(port))
1279  {
1280  throw new ArgumentOutOfRangeException("port");
1281  }
1282  if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6)
1283  {
1284  throw new NotSupportedException(SR.GetString("net_invalidversion"));
1285  }
1286  Exception ex = null;
1287  foreach (IPAddress iPAddress in addresses)
1288  {
1289  if (CanTryAddressFamily(iPAddress.AddressFamily))
1290  {
1291  try
1292  {
1293  Connect(new IPEndPoint(iPAddress, port));
1294  ex = null;
1295  }
1296  catch (Exception ex2)
1297  {
1298  if (NclUtilities.IsFatal(ex2))
1299  {
1300  throw;
1301  }
1302  ex = ex2;
1303  continue;
1304  }
1305  break;
1306  }
1307  }
1308  if (ex != null)
1309  {
1310  throw ex;
1311  }
1312  if (!Connected)
1313  {
1314  throw new ArgumentException(SR.GetString("net_invalidAddressList"), "addresses");
1315  }
1316  if (s_LoggingEnabled)
1317  {
1318  Logging.Exit(Logging.Sockets, this, "Connect", null);
1319  }
1320  }
1321 
1323  public void Close()
1324  {
1325  if (s_LoggingEnabled)
1326  {
1327  Logging.Enter(Logging.Sockets, this, "Close", null);
1328  }
1329  ((IDisposable)this).Dispose();
1330  if (s_LoggingEnabled)
1331  {
1332  Logging.Exit(Logging.Sockets, this, "Close", null);
1333  }
1334  }
1335 
1338  public void Close(int timeout)
1339  {
1340  if (timeout < -1)
1341  {
1342  throw new ArgumentOutOfRangeException("timeout");
1343  }
1344  m_CloseTimeout = timeout;
1345  ((IDisposable)this).Dispose();
1346  }
1347 
1352  public void Listen(int backlog)
1353  {
1354  if (s_LoggingEnabled)
1355  {
1356  Logging.Enter(Logging.Sockets, this, "Listen", backlog);
1357  }
1358  if (CleanedUp)
1359  {
1360  throw new ObjectDisposedException(GetType().FullName);
1361  }
1362  if (UnsafeNclNativeMethods.OSSOCK.listen(m_Handle, backlog) != 0)
1363  {
1364  SocketException ex = new SocketException();
1365  UpdateStatusAfterSocketError(ex);
1366  if (s_LoggingEnabled)
1367  {
1368  Logging.Exception(Logging.Sockets, this, "Listen", ex);
1369  }
1370  throw ex;
1371  }
1372  isListening = true;
1373  if (s_LoggingEnabled)
1374  {
1375  Logging.Exit(Logging.Sockets, this, "Listen", "");
1376  }
1377  }
1378 
1384  public Socket Accept()
1385  {
1386  if (s_LoggingEnabled)
1387  {
1388  Logging.Enter(Logging.Sockets, this, "Accept", "");
1389  }
1390  if (CleanedUp)
1391  {
1392  throw new ObjectDisposedException(GetType().FullName);
1393  }
1394  if (m_RightEndPoint == null)
1395  {
1396  throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
1397  }
1398  if (!isListening)
1399  {
1400  throw new InvalidOperationException(SR.GetString("net_sockets_mustlisten"));
1401  }
1402  if (m_IsDisconnected)
1403  {
1404  throw new InvalidOperationException(SR.GetString("net_sockets_disconnectedAccept"));
1405  }
1406  ValidateBlockingMode();
1407  SocketAddress socketAddress = m_RightEndPoint.Serialize();
1408  SafeCloseSocket safeCloseSocket = SafeCloseSocket.Accept(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size);
1409  if (safeCloseSocket.IsInvalid)
1410  {
1411  SocketException ex = new SocketException();
1412  UpdateStatusAfterSocketError(ex);
1413  if (s_LoggingEnabled)
1414  {
1415  Logging.Exception(Logging.Sockets, this, "Accept", ex);
1416  }
1417  throw ex;
1418  }
1419  Socket socket = CreateAcceptSocket(safeCloseSocket, m_RightEndPoint.Create(socketAddress), needCancelSelect: false);
1420  if (s_LoggingEnabled)
1421  {
1422  Logging.PrintInfo(Logging.Sockets, socket, SR.GetString("net_log_socket_accepted", socket.RemoteEndPoint, socket.LocalEndPoint));
1423  Logging.Exit(Logging.Sockets, this, "Accept", socket);
1424  }
1425  return socket;
1426  }
1427 
1440  public int Send(byte[] buffer, int size, SocketFlags socketFlags)
1441  {
1442  return Send(buffer, 0, size, socketFlags);
1443  }
1444 
1453  public int Send(byte[] buffer, SocketFlags socketFlags)
1454  {
1455  return Send(buffer, 0, (buffer != null) ? buffer.Length : 0, socketFlags);
1456  }
1457 
1465  public int Send(byte[] buffer)
1466  {
1467  return Send(buffer, 0, (buffer != null) ? buffer.Length : 0, SocketFlags.None);
1468  }
1469 
1479  public int Send(IList<ArraySegment<byte>> buffers)
1480  {
1481  return Send(buffers, SocketFlags.None);
1482  }
1483 
1494  public int Send(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1495  {
1496  SocketError errorCode;
1497  int result = Send(buffers, socketFlags, out errorCode);
1498  if (errorCode != 0)
1499  {
1500  throw new SocketException(errorCode);
1501  }
1502  return result;
1503  }
1504 
1516  public int Send(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1517  {
1518  if (s_LoggingEnabled)
1519  {
1520  Logging.Enter(Logging.Sockets, this, "Send", "");
1521  }
1522  if (CleanedUp)
1523  {
1524  throw new ObjectDisposedException(GetType().FullName);
1525  }
1526  if (buffers == null)
1527  {
1528  throw new ArgumentNullException("buffers");
1529  }
1530  if (buffers.Count == 0)
1531  {
1532  throw new ArgumentException(SR.GetString("net_sockets_zerolist", "buffers"), "buffers");
1533  }
1534  ValidateBlockingMode();
1535  errorCode = SocketError.Success;
1536  int count = buffers.Count;
1537  WSABuffer[] array = new WSABuffer[count];
1538  GCHandle[] array2 = null;
1539  int bytesTransferred;
1540  try
1541  {
1542  array2 = new GCHandle[count];
1543  for (int i = 0; i < count; i++)
1544  {
1545  ArraySegment<byte> segment = buffers[i];
1546  ValidationHelper.ValidateSegment(segment);
1547  array2[i] = GCHandle.Alloc(segment.Array, GCHandleType.Pinned);
1548  array[i].Length = segment.Count;
1549  array[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement((Array)segment.Array, segment.Offset);
1550  }
1551  errorCode = UnsafeNclNativeMethods.OSSOCK.WSASend_Blocking(m_Handle.DangerousGetHandle(), array, count, out bytesTransferred, socketFlags, SafeNativeOverlapped.Zero, IntPtr.Zero);
1552  if (errorCode == SocketError.SocketError)
1553  {
1554  errorCode = (SocketError)Marshal.GetLastWin32Error();
1555  }
1556  }
1557  finally
1558  {
1559  if (array2 != null)
1560  {
1561  for (int j = 0; j < array2.Length; j++)
1562  {
1563  if (array2[j].IsAllocated)
1564  {
1565  array2[j].Free();
1566  }
1567  }
1568  }
1569  }
1570  if (errorCode != 0)
1571  {
1572  UpdateStatusAfterSocketError(errorCode);
1573  if (s_LoggingEnabled)
1574  {
1575  Logging.Exception(Logging.Sockets, this, "Send", new SocketException(errorCode));
1576  Logging.Exit(Logging.Sockets, this, "Send", 0);
1577  }
1578  return 0;
1579  }
1580  if (s_PerfCountersEnabled && bytesTransferred > 0)
1581  {
1582  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, bytesTransferred);
1583  if (Transport == TransportType.Udp)
1584  {
1585  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
1586  }
1587  }
1588  if (s_LoggingEnabled)
1589  {
1590  Logging.Exit(Logging.Sockets, this, "Send", bytesTransferred);
1591  }
1592  return bytesTransferred;
1593  }
1594 
1602  public void SendFile(string fileName)
1603  {
1604  SendFile(fileName, null, null, TransmitFileOptions.UseDefaultWorkerThread);
1605  }
1606 
1617  public void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
1618  {
1619  if (s_LoggingEnabled)
1620  {
1621  Logging.Enter(Logging.Sockets, this, "SendFile", "");
1622  }
1623  if (CleanedUp)
1624  {
1625  throw new ObjectDisposedException(GetType().FullName);
1626  }
1627  if (!Connected)
1628  {
1629  throw new NotSupportedException(SR.GetString("net_notconnected"));
1630  }
1631  ValidateBlockingMode();
1632  TransmitFileOverlappedAsyncResult transmitFileOverlappedAsyncResult = new TransmitFileOverlappedAsyncResult(this);
1633  FileStream fileStream = null;
1634  if (fileName != null && fileName.Length > 0)
1635  {
1636  fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
1637  }
1638  SafeHandle safeHandle = null;
1639  if (fileStream != null)
1640  {
1641  ExceptionHelper.UnmanagedPermission.Assert();
1642  try
1643  {
1644  safeHandle = fileStream.SafeFileHandle;
1645  }
1646  finally
1647  {
1649  }
1650  }
1651  SocketError socketError = SocketError.Success;
1652  try
1653  {
1654  transmitFileOverlappedAsyncResult.SetUnmanagedStructures(preBuffer, postBuffer, fileStream, TransmitFileOptions.UseDefaultWorkerThread, sync: true);
1655  if ((safeHandle != null) ? (!UnsafeNclNativeMethods.OSSOCK.TransmitFile_Blocking(m_Handle.DangerousGetHandle(), safeHandle, 0, 0, SafeNativeOverlapped.Zero, transmitFileOverlappedAsyncResult.TransmitFileBuffers, flags)) : (!UnsafeNclNativeMethods.OSSOCK.TransmitFile_Blocking2(m_Handle.DangerousGetHandle(), IntPtr.Zero, 0, 0, SafeNativeOverlapped.Zero, transmitFileOverlappedAsyncResult.TransmitFileBuffers, flags)))
1656  {
1657  socketError = (SocketError)Marshal.GetLastWin32Error();
1658  }
1659  }
1660  finally
1661  {
1662  transmitFileOverlappedAsyncResult.SyncReleaseUnmanagedStructures();
1663  }
1664  if (socketError != 0)
1665  {
1666  SocketException ex = new SocketException(socketError);
1667  UpdateStatusAfterSocketError(ex);
1668  if (s_LoggingEnabled)
1669  {
1670  Logging.Exception(Logging.Sockets, this, "SendFile", ex);
1671  }
1672  throw ex;
1673  }
1674  if ((transmitFileOverlappedAsyncResult.Flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0)
1675  {
1676  SetToDisconnected();
1677  m_RemoteEndPoint = null;
1678  }
1679  if (s_LoggingEnabled)
1680  {
1681  Logging.Exit(Logging.Sockets, this, "SendFile", socketError);
1682  }
1683  }
1684 
1701  public int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags)
1702  {
1703  SocketError errorCode;
1704  int result = Send(buffer, offset, size, socketFlags, out errorCode);
1705  if (errorCode != 0)
1706  {
1707  throw new SocketException(errorCode);
1708  }
1709  return result;
1710  }
1711 
1729  public unsafe int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
1730  {
1731  if (s_LoggingEnabled)
1732  {
1733  Logging.Enter(Logging.Sockets, this, "Send", "");
1734  }
1735  if (CleanedUp)
1736  {
1737  throw new ObjectDisposedException(GetType().FullName);
1738  }
1739  if (buffer == null)
1740  {
1741  throw new ArgumentNullException("buffer");
1742  }
1743  if (offset < 0 || offset > buffer.Length)
1744  {
1745  throw new ArgumentOutOfRangeException("offset");
1746  }
1747  if (size < 0 || size > buffer.Length - offset)
1748  {
1749  throw new ArgumentOutOfRangeException("size");
1750  }
1751  errorCode = SocketError.Success;
1752  ValidateBlockingMode();
1753  int num;
1754  if (buffer.Length == 0)
1755  {
1756  num = UnsafeNclNativeMethods.OSSOCK.send(m_Handle.DangerousGetHandle(), null, 0, socketFlags);
1757  }
1758  else
1759  {
1760  fixed (byte* ptr = buffer)
1761  {
1762  num = UnsafeNclNativeMethods.OSSOCK.send(m_Handle.DangerousGetHandle(), ptr + offset, size, socketFlags);
1763  }
1764  }
1765  if (num == -1)
1766  {
1767  errorCode = (SocketError)Marshal.GetLastWin32Error();
1768  UpdateStatusAfterSocketError(errorCode);
1769  if (s_LoggingEnabled)
1770  {
1771  Logging.Exception(Logging.Sockets, this, "Send", new SocketException(errorCode));
1772  Logging.Exit(Logging.Sockets, this, "Send", 0);
1773  }
1774  return 0;
1775  }
1776  if (s_PerfCountersEnabled && num > 0)
1777  {
1778  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, num);
1779  if (Transport == TransportType.Udp)
1780  {
1781  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
1782  }
1783  }
1784  if (s_LoggingEnabled)
1785  {
1786  Logging.Dump(Logging.Sockets, this, "Send", buffer, offset, size);
1787  }
1788  if (s_LoggingEnabled)
1789  {
1790  Logging.Exit(Logging.Sockets, this, "Send", num);
1791  }
1792  return num;
1793  }
1794 
1814  public unsafe int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
1815  {
1816  if (s_LoggingEnabled)
1817  {
1818  Logging.Enter(Logging.Sockets, this, "SendTo", "");
1819  }
1820  if (CleanedUp)
1821  {
1822  throw new ObjectDisposedException(GetType().FullName);
1823  }
1824  if (buffer == null)
1825  {
1826  throw new ArgumentNullException("buffer");
1827  }
1828  if (remoteEP == null)
1829  {
1830  throw new ArgumentNullException("remoteEP");
1831  }
1832  if (offset < 0 || offset > buffer.Length)
1833  {
1834  throw new ArgumentOutOfRangeException("offset");
1835  }
1836  if (size < 0 || size > buffer.Length - offset)
1837  {
1838  throw new ArgumentOutOfRangeException("size");
1839  }
1840  ValidateBlockingMode();
1841  EndPoint remoteEP2 = remoteEP;
1842  SocketAddress socketAddress = CheckCacheRemote(ref remoteEP2, isOverwrite: false);
1843  int num;
1844  if (buffer.Length == 0)
1845  {
1846  num = UnsafeNclNativeMethods.OSSOCK.sendto(m_Handle.DangerousGetHandle(), null, 0, socketFlags, socketAddress.m_Buffer, socketAddress.m_Size);
1847  }
1848  else
1849  {
1850  fixed (byte* ptr = buffer)
1851  {
1852  num = UnsafeNclNativeMethods.OSSOCK.sendto(m_Handle.DangerousGetHandle(), ptr + offset, size, socketFlags, socketAddress.m_Buffer, socketAddress.m_Size);
1853  }
1854  }
1855  if (num == -1)
1856  {
1857  SocketException ex = new SocketException();
1858  UpdateStatusAfterSocketError(ex);
1859  if (s_LoggingEnabled)
1860  {
1861  Logging.Exception(Logging.Sockets, this, "SendTo", ex);
1862  }
1863  throw ex;
1864  }
1865  if (m_RightEndPoint == null)
1866  {
1867  m_RightEndPoint = remoteEP2;
1868  }
1869  if (s_PerfCountersEnabled && num > 0)
1870  {
1871  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, num);
1872  if (Transport == TransportType.Udp)
1873  {
1874  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
1875  }
1876  }
1877  if (s_LoggingEnabled)
1878  {
1879  Logging.Dump(Logging.Sockets, this, "SendTo", buffer, offset, size);
1880  }
1881  if (s_LoggingEnabled)
1882  {
1883  Logging.Exit(Logging.Sockets, this, "SendTo", num);
1884  }
1885  return num;
1886  }
1887 
1900  public int SendTo(byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP)
1901  {
1902  return SendTo(buffer, 0, size, socketFlags, remoteEP);
1903  }
1904 
1915  public int SendTo(byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP)
1916  {
1917  return SendTo(buffer, 0, (buffer != null) ? buffer.Length : 0, socketFlags, remoteEP);
1918  }
1919 
1929  public int SendTo(byte[] buffer, EndPoint remoteEP)
1930  {
1931  return SendTo(buffer, 0, (buffer != null) ? buffer.Length : 0, SocketFlags.None, remoteEP);
1932  }
1933 
1946  public int Receive(byte[] buffer, int size, SocketFlags socketFlags)
1947  {
1948  return Receive(buffer, 0, size, socketFlags);
1949  }
1950 
1960  public int Receive(byte[] buffer, SocketFlags socketFlags)
1961  {
1962  return Receive(buffer, 0, (buffer != null) ? buffer.Length : 0, socketFlags);
1963  }
1964 
1973  public int Receive(byte[] buffer)
1974  {
1975  return Receive(buffer, 0, (buffer != null) ? buffer.Length : 0, SocketFlags.None);
1976  }
1977 
1995  public int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags)
1996  {
1997  SocketError errorCode;
1998  int result = Receive(buffer, offset, size, socketFlags, out errorCode);
1999  if (errorCode != 0)
2000  {
2001  throw new SocketException(errorCode);
2002  }
2003  return result;
2004  }
2005 
2024  public unsafe int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
2025  {
2026  if (s_LoggingEnabled)
2027  {
2028  Logging.Enter(Logging.Sockets, this, "Receive", "");
2029  }
2030  if (CleanedUp)
2031  {
2032  throw new ObjectDisposedException(GetType().FullName);
2033  }
2034  if (buffer == null)
2035  {
2036  throw new ArgumentNullException("buffer");
2037  }
2038  if (offset < 0 || offset > buffer.Length)
2039  {
2040  throw new ArgumentOutOfRangeException("offset");
2041  }
2042  if (size < 0 || size > buffer.Length - offset)
2043  {
2044  throw new ArgumentOutOfRangeException("size");
2045  }
2046  ValidateBlockingMode();
2047  errorCode = SocketError.Success;
2048  int num;
2049  if (buffer.Length == 0)
2050  {
2051  num = UnsafeNclNativeMethods.OSSOCK.recv(m_Handle.DangerousGetHandle(), null, 0, socketFlags);
2052  }
2053  else
2054  {
2055  fixed (byte* ptr = buffer)
2056  {
2057  num = UnsafeNclNativeMethods.OSSOCK.recv(m_Handle.DangerousGetHandle(), ptr + offset, size, socketFlags);
2058  }
2059  }
2060  if (num == -1)
2061  {
2062  errorCode = (SocketError)Marshal.GetLastWin32Error();
2063  UpdateStatusAfterSocketError(errorCode);
2064  if (s_LoggingEnabled)
2065  {
2066  Logging.Exception(Logging.Sockets, this, "Receive", new SocketException(errorCode));
2067  Logging.Exit(Logging.Sockets, this, "Receive", 0);
2068  }
2069  return 0;
2070  }
2071  if (s_PerfCountersEnabled)
2072  {
2073  bool flag = (socketFlags & SocketFlags.Peek) != SocketFlags.None;
2074  if (num > 0 && !flag)
2075  {
2076  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, num);
2077  if (Transport == TransportType.Udp)
2078  {
2079  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
2080  }
2081  }
2082  }
2083  if (s_LoggingEnabled)
2084  {
2085  Logging.Dump(Logging.Sockets, this, "Receive", buffer, offset, num);
2086  }
2087  if (s_LoggingEnabled)
2088  {
2089  Logging.Exit(Logging.Sockets, this, "Receive", num);
2090  }
2091  return num;
2092  }
2093 
2100  public int Receive(IList<ArraySegment<byte>> buffers)
2101  {
2102  return Receive(buffers, SocketFlags.None);
2103  }
2104 
2114  public int Receive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
2115  {
2116  SocketError errorCode;
2117  int result = Receive(buffers, socketFlags, out errorCode);
2118  if (errorCode != 0)
2119  {
2120  throw new SocketException(errorCode);
2121  }
2122  return result;
2123  }
2124 
2135  public int Receive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
2136  {
2137  if (s_LoggingEnabled)
2138  {
2139  Logging.Enter(Logging.Sockets, this, "Receive", "");
2140  }
2141  if (CleanedUp)
2142  {
2143  throw new ObjectDisposedException(GetType().FullName);
2144  }
2145  if (buffers == null)
2146  {
2147  throw new ArgumentNullException("buffers");
2148  }
2149  if (buffers.Count == 0)
2150  {
2151  throw new ArgumentException(SR.GetString("net_sockets_zerolist", "buffers"), "buffers");
2152  }
2153  ValidateBlockingMode();
2154  int count = buffers.Count;
2155  WSABuffer[] array = new WSABuffer[count];
2156  GCHandle[] array2 = null;
2157  errorCode = SocketError.Success;
2158  int bytesTransferred;
2159  try
2160  {
2161  array2 = new GCHandle[count];
2162  for (int i = 0; i < count; i++)
2163  {
2164  ArraySegment<byte> segment = buffers[i];
2165  ValidationHelper.ValidateSegment(segment);
2166  array2[i] = GCHandle.Alloc(segment.Array, GCHandleType.Pinned);
2167  array[i].Length = segment.Count;
2168  array[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement((Array)segment.Array, segment.Offset);
2169  }
2170  errorCode = UnsafeNclNativeMethods.OSSOCK.WSARecv_Blocking(m_Handle.DangerousGetHandle(), array, count, out bytesTransferred, ref socketFlags, SafeNativeOverlapped.Zero, IntPtr.Zero);
2171  if (errorCode == SocketError.SocketError)
2172  {
2173  errorCode = (SocketError)Marshal.GetLastWin32Error();
2174  }
2175  }
2176  finally
2177  {
2178  if (array2 != null)
2179  {
2180  for (int j = 0; j < array2.Length; j++)
2181  {
2182  if (array2[j].IsAllocated)
2183  {
2184  array2[j].Free();
2185  }
2186  }
2187  }
2188  }
2189  if (errorCode != 0)
2190  {
2191  UpdateStatusAfterSocketError(errorCode);
2192  if (s_LoggingEnabled)
2193  {
2194  Logging.Exception(Logging.Sockets, this, "Receive", new SocketException(errorCode));
2195  Logging.Exit(Logging.Sockets, this, "Receive", 0);
2196  }
2197  return 0;
2198  }
2199  if (s_PerfCountersEnabled)
2200  {
2201  bool flag = (socketFlags & SocketFlags.Peek) != SocketFlags.None;
2202  if (bytesTransferred > 0 && !flag)
2203  {
2204  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, bytesTransferred);
2205  if (Transport == TransportType.Udp)
2206  {
2207  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
2208  }
2209  }
2210  }
2211  if (s_LoggingEnabled)
2212  {
2213  Logging.Exit(Logging.Sockets, this, "Receive", bytesTransferred);
2214  }
2215  return bytesTransferred;
2216  }
2217 
2238  public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
2239  {
2240  if (s_LoggingEnabled)
2241  {
2242  Logging.Enter(Logging.Sockets, this, "ReceiveMessageFrom", "");
2243  }
2244  if (CleanedUp)
2245  {
2246  throw new ObjectDisposedException(GetType().FullName);
2247  }
2248  if (buffer == null)
2249  {
2250  throw new ArgumentNullException("buffer");
2251  }
2252  if (remoteEP == null)
2253  {
2254  throw new ArgumentNullException("remoteEP");
2255  }
2256  if (!CanTryAddressFamily(remoteEP.AddressFamily))
2257  {
2258  throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", remoteEP.AddressFamily, addressFamily), "remoteEP");
2259  }
2260  if (offset < 0 || offset > buffer.Length)
2261  {
2262  throw new ArgumentOutOfRangeException("offset");
2263  }
2264  if (size < 0 || size > buffer.Length - offset)
2265  {
2266  throw new ArgumentOutOfRangeException("size");
2267  }
2268  if (m_RightEndPoint == null)
2269  {
2270  throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
2271  }
2272  ValidateBlockingMode();
2273  EndPoint remoteEP2 = remoteEP;
2274  SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP2);
2275  ReceiveMessageOverlappedAsyncResult receiveMessageOverlappedAsyncResult = new ReceiveMessageOverlappedAsyncResult(this, null, null);
2276  receiveMessageOverlappedAsyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags);
2277  SocketAddress socketAddress2 = remoteEP2.Serialize();
2278  int bytesTransferred = 0;
2279  SocketError socketError = SocketError.Success;
2280  SetReceivingPacketInformation();
2281  try
2282  {
2283  if (WSARecvMsg_Blocking(m_Handle.DangerousGetHandle(), Marshal.UnsafeAddrOfPinnedArrayElement((Array)receiveMessageOverlappedAsyncResult.m_MessageBuffer, 0), out bytesTransferred, IntPtr.Zero, IntPtr.Zero) == SocketError.SocketError)
2284  {
2285  socketError = (SocketError)Marshal.GetLastWin32Error();
2286  }
2287  }
2288  finally
2289  {
2290  receiveMessageOverlappedAsyncResult.SyncReleaseUnmanagedStructures();
2291  }
2292  if (socketError != 0 && socketError != SocketError.MessageSize)
2293  {
2294  SocketException ex = new SocketException(socketError);
2295  UpdateStatusAfterSocketError(ex);
2296  if (s_LoggingEnabled)
2297  {
2298  Logging.Exception(Logging.Sockets, this, "ReceiveMessageFrom", ex);
2299  }
2300  throw ex;
2301  }
2302  if (!socketAddress2.Equals(receiveMessageOverlappedAsyncResult.m_SocketAddress))
2303  {
2304  try
2305  {
2306  remoteEP = remoteEP2.Create(receiveMessageOverlappedAsyncResult.m_SocketAddress);
2307  }
2308  catch
2309  {
2310  }
2311  if (m_RightEndPoint == null)
2312  {
2313  m_RightEndPoint = remoteEP2;
2314  }
2315  }
2316  socketFlags = receiveMessageOverlappedAsyncResult.m_flags;
2317  ipPacketInformation = receiveMessageOverlappedAsyncResult.m_IPPacketInformation;
2318  if (s_LoggingEnabled)
2319  {
2320  Logging.Exit(Logging.Sockets, this, "ReceiveMessageFrom", socketError);
2321  }
2322  return bytesTransferred;
2323  }
2324 
2343  public unsafe int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
2344  {
2345  if (s_LoggingEnabled)
2346  {
2347  Logging.Enter(Logging.Sockets, this, "ReceiveFrom", "");
2348  }
2349  if (CleanedUp)
2350  {
2351  throw new ObjectDisposedException(GetType().FullName);
2352  }
2353  if (buffer == null)
2354  {
2355  throw new ArgumentNullException("buffer");
2356  }
2357  if (remoteEP == null)
2358  {
2359  throw new ArgumentNullException("remoteEP");
2360  }
2361  if (!CanTryAddressFamily(remoteEP.AddressFamily))
2362  {
2363  throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", remoteEP.AddressFamily, addressFamily), "remoteEP");
2364  }
2365  if (offset < 0 || offset > buffer.Length)
2366  {
2367  throw new ArgumentOutOfRangeException("offset");
2368  }
2369  if (size < 0 || size > buffer.Length - offset)
2370  {
2371  throw new ArgumentOutOfRangeException("size");
2372  }
2373  if (m_RightEndPoint == null)
2374  {
2375  throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
2376  }
2377  ValidateBlockingMode();
2378  EndPoint remoteEP2 = remoteEP;
2379  SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP2);
2380  SocketAddress socketAddress2 = remoteEP2.Serialize();
2381  int num;
2382  if (buffer.Length == 0)
2383  {
2384  num = UnsafeNclNativeMethods.OSSOCK.recvfrom(m_Handle.DangerousGetHandle(), null, 0, socketFlags, socketAddress.m_Buffer, ref socketAddress.m_Size);
2385  }
2386  else
2387  {
2388  fixed (byte* ptr = buffer)
2389  {
2390  num = UnsafeNclNativeMethods.OSSOCK.recvfrom(m_Handle.DangerousGetHandle(), ptr + offset, size, socketFlags, socketAddress.m_Buffer, ref socketAddress.m_Size);
2391  }
2392  }
2393  SocketException ex = null;
2394  if (num == -1)
2395  {
2396  ex = new SocketException();
2397  UpdateStatusAfterSocketError(ex);
2398  if (s_LoggingEnabled)
2399  {
2400  Logging.Exception(Logging.Sockets, this, "ReceiveFrom", ex);
2401  }
2402  if (ex.ErrorCode != 10040)
2403  {
2404  throw ex;
2405  }
2406  }
2407  if (!socketAddress2.Equals(socketAddress))
2408  {
2409  try
2410  {
2411  remoteEP = remoteEP2.Create(socketAddress);
2412  }
2413  catch
2414  {
2415  }
2416  if (m_RightEndPoint == null)
2417  {
2418  m_RightEndPoint = remoteEP2;
2419  }
2420  }
2421  if (ex != null)
2422  {
2423  throw ex;
2424  }
2425  if (s_PerfCountersEnabled && num > 0)
2426  {
2427  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, num);
2428  if (Transport == TransportType.Udp)
2429  {
2430  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
2431  }
2432  }
2433  if (s_LoggingEnabled)
2434  {
2435  Logging.Dump(Logging.Sockets, this, "ReceiveFrom", buffer, offset, size);
2436  }
2437  if (s_LoggingEnabled)
2438  {
2439  Logging.Exit(Logging.Sockets, this, "ReceiveFrom", num);
2440  }
2441  return num;
2442  }
2443 
2460  public int ReceiveFrom(byte[] buffer, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
2461  {
2462  return ReceiveFrom(buffer, 0, size, socketFlags, ref remoteEP);
2463  }
2464 
2476  public int ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP)
2477  {
2478  return ReceiveFrom(buffer, 0, (buffer != null) ? buffer.Length : 0, socketFlags, ref remoteEP);
2479  }
2480 
2491  public int ReceiveFrom(byte[] buffer, ref EndPoint remoteEP)
2492  {
2493  return ReceiveFrom(buffer, 0, (buffer != null) ? buffer.Length : 0, SocketFlags.None, ref remoteEP);
2494  }
2495 
2505  public int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue)
2506  {
2507  if (CleanedUp)
2508  {
2509  throw new ObjectDisposedException(GetType().FullName);
2510  }
2511  if (ioControlCode == -2147195266)
2512  {
2513  throw new InvalidOperationException(SR.GetString("net_sockets_useblocking"));
2514  }
2515  ExceptionHelper.UnmanagedPermission.Demand();
2516  int bytesTransferred = 0;
2517  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking(m_Handle.DangerousGetHandle(), ioControlCode, optionInValue, (optionInValue != null) ? optionInValue.Length : 0, optionOutValue, (optionOutValue != null) ? optionOutValue.Length : 0, out bytesTransferred, SafeNativeOverlapped.Zero, IntPtr.Zero);
2518  if (socketError == SocketError.SocketError)
2519  {
2520  SocketException ex = new SocketException();
2521  UpdateStatusAfterSocketError(ex);
2522  if (s_LoggingEnabled)
2523  {
2524  Logging.Exception(Logging.Sockets, this, "IOControl", ex);
2525  }
2526  throw ex;
2527  }
2528  return bytesTransferred;
2529  }
2530 
2539  public int IOControl(IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue)
2540  {
2541  return IOControl((int)ioControlCode, optionInValue, optionOutValue);
2542  }
2543 
2544  internal int IOControl(IOControlCode ioControlCode, IntPtr optionInValue, int inValueSize, IntPtr optionOutValue, int outValueSize)
2545  {
2546  if (CleanedUp)
2547  {
2548  throw new ObjectDisposedException(GetType().FullName);
2549  }
2550  if ((int)ioControlCode == -2147195266)
2551  {
2552  throw new InvalidOperationException(SR.GetString("net_sockets_useblocking"));
2553  }
2554  int bytesTransferred = 0;
2555  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.WSAIoctl_Blocking_Internal(m_Handle.DangerousGetHandle(), (uint)ioControlCode, optionInValue, inValueSize, optionOutValue, outValueSize, out bytesTransferred, SafeNativeOverlapped.Zero, IntPtr.Zero);
2556  if (socketError == SocketError.SocketError)
2557  {
2558  SocketException ex = new SocketException();
2559  UpdateStatusAfterSocketError(ex);
2560  if (s_LoggingEnabled)
2561  {
2562  Logging.Exception(Logging.Sockets, this, "IOControl", ex);
2563  }
2564  throw ex;
2565  }
2566  return bytesTransferred;
2567  }
2568 
2574  {
2575  if (level == IPProtectionLevel.Unspecified)
2576  {
2577  throw new ArgumentException(SR.GetString("net_sockets_invalid_optionValue_all"), "level");
2578  }
2579  if (addressFamily == AddressFamily.InterNetworkV6)
2580  {
2581  SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPProtectionLevel, (int)level);
2582  return;
2583  }
2584  if (addressFamily == AddressFamily.InterNetwork)
2585  {
2586  SetSocketOption(SocketOptionLevel.IP, SocketOptionName.IPProtectionLevel, (int)level);
2587  return;
2588  }
2589  throw new NotSupportedException(SR.GetString("net_invalidversion"));
2590  }
2591 
2598  public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
2599  {
2600  if (CleanedUp)
2601  {
2602  throw new ObjectDisposedException(GetType().FullName);
2603  }
2604  CheckSetOptionPermissions(optionLevel, optionName);
2605  SetSocketOption(optionLevel, optionName, optionValue, silent: false);
2606  }
2607 
2614  public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
2615  {
2616  if (CleanedUp)
2617  {
2618  throw new ObjectDisposedException(GetType().FullName);
2619  }
2620  CheckSetOptionPermissions(optionLevel, optionName);
2621  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(m_Handle, optionLevel, optionName, optionValue, (optionValue != null) ? optionValue.Length : 0);
2622  if (socketError == SocketError.SocketError)
2623  {
2624  SocketException ex = new SocketException();
2625  UpdateStatusAfterSocketError(ex);
2626  if (s_LoggingEnabled)
2627  {
2628  Logging.Exception(Logging.Sockets, this, "SetSocketOption", ex);
2629  }
2630  throw ex;
2631  }
2632  }
2633 
2640  public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
2641  {
2642  SetSocketOption(optionLevel, optionName, optionValue ? 1 : 0);
2643  }
2644 
2653  public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue)
2654  {
2655  if (CleanedUp)
2656  {
2657  throw new ObjectDisposedException(GetType().FullName);
2658  }
2659  if (optionValue == null)
2660  {
2661  throw new ArgumentNullException("optionValue");
2662  }
2663  CheckSetOptionPermissions(optionLevel, optionName);
2664  if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger)
2665  {
2666  LingerOption lingerOption = optionValue as LingerOption;
2667  if (lingerOption == null)
2668  {
2669  throw new ArgumentException(SR.GetString("net_sockets_invalid_optionValue", "LingerOption"), "optionValue");
2670  }
2671  if (lingerOption.LingerTime < 0 || lingerOption.LingerTime > 65535)
2672  {
2673  throw new ArgumentException(SR.GetString("ArgumentOutOfRange_Bounds_Lower_Upper", 0, 65535), "optionValue.LingerTime");
2674  }
2675  setLingerOption(lingerOption);
2676  }
2677  else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership))
2678  {
2679  MulticastOption multicastOption = optionValue as MulticastOption;
2680  if (multicastOption == null)
2681  {
2682  throw new ArgumentException(SR.GetString("net_sockets_invalid_optionValue", "MulticastOption"), "optionValue");
2683  }
2684  setMulticastOption(optionName, multicastOption);
2685  }
2686  else
2687  {
2688  if (optionLevel != SocketOptionLevel.IPv6 || (optionName != SocketOptionName.AddMembership && optionName != SocketOptionName.DropMembership))
2689  {
2690  throw new ArgumentException(SR.GetString("net_sockets_invalid_optionValue_all"), "optionValue");
2691  }
2692  IPv6MulticastOption pv6MulticastOption = optionValue as IPv6MulticastOption;
2693  if (pv6MulticastOption == null)
2694  {
2695  throw new ArgumentException(SR.GetString("net_sockets_invalid_optionValue", "IPv6MulticastOption"), "optionValue");
2696  }
2697  setIPv6MulticastOption(optionName, pv6MulticastOption);
2698  }
2699  }
2700 
2708  public object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName)
2709  {
2710  if (CleanedUp)
2711  {
2712  throw new ObjectDisposedException(GetType().FullName);
2713  }
2714  if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger)
2715  {
2716  return getLingerOpt();
2717  }
2718  if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership))
2719  {
2720  return getMulticastOpt(optionName);
2721  }
2722  if (optionLevel == SocketOptionLevel.IPv6 && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership))
2723  {
2724  return getIPv6MulticastOpt(optionName);
2725  }
2726  int optionValue = 0;
2727  int optionLength = 4;
2728  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.getsockopt(m_Handle, optionLevel, optionName, out optionValue, ref optionLength);
2729  if (socketError == SocketError.SocketError)
2730  {
2731  SocketException ex = new SocketException();
2732  UpdateStatusAfterSocketError(ex);
2733  if (s_LoggingEnabled)
2734  {
2735  Logging.Exception(Logging.Sockets, this, "GetSocketOption", ex);
2736  }
2737  throw ex;
2738  }
2739  return optionValue;
2740  }
2741 
2748  public void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
2749  {
2750  if (CleanedUp)
2751  {
2752  throw new ObjectDisposedException(GetType().FullName);
2753  }
2754  int optionLength = (optionValue != null) ? optionValue.Length : 0;
2755  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.getsockopt(m_Handle, optionLevel, optionName, optionValue, ref optionLength);
2756  if (socketError == SocketError.SocketError)
2757  {
2758  SocketException ex = new SocketException();
2759  UpdateStatusAfterSocketError(ex);
2760  if (s_LoggingEnabled)
2761  {
2762  Logging.Exception(Logging.Sockets, this, "GetSocketOption", ex);
2763  }
2764  throw ex;
2765  }
2766  }
2767 
2775  public byte[] GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength)
2776  {
2777  if (CleanedUp)
2778  {
2779  throw new ObjectDisposedException(GetType().FullName);
2780  }
2781  byte[] array = new byte[optionLength];
2782  int optionLength2 = optionLength;
2783  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.getsockopt(m_Handle, optionLevel, optionName, array, ref optionLength2);
2784  if (socketError == SocketError.SocketError)
2785  {
2786  SocketException ex = new SocketException();
2787  UpdateStatusAfterSocketError(ex);
2788  if (s_LoggingEnabled)
2789  {
2790  Logging.Exception(Logging.Sockets, this, "GetSocketOption", ex);
2791  }
2792  throw ex;
2793  }
2794  if (optionLength != optionLength2)
2795  {
2796  byte[] array2 = new byte[optionLength2];
2797  Buffer.BlockCopy(array, 0, array2, 0, optionLength2);
2798  array = array2;
2799  }
2800  return array;
2801  }
2802 
2823  public bool Poll(int microSeconds, SelectMode mode)
2824  {
2825  if (CleanedUp)
2826  {
2827  throw new ObjectDisposedException(GetType().FullName);
2828  }
2829  IntPtr intPtr = m_Handle.DangerousGetHandle();
2830  IntPtr[] array = new IntPtr[2]
2831  {
2832  (IntPtr)1,
2833  intPtr
2834  };
2835  TimeValue socketTime = default(TimeValue);
2836  int num;
2837  if (microSeconds != -1)
2838  {
2839  MicrosecondsToTimeValue((uint)microSeconds, ref socketTime);
2840  num = UnsafeNclNativeMethods.OSSOCK.select(0, (mode == SelectMode.SelectRead) ? array : null, (mode == SelectMode.SelectWrite) ? array : null, (mode == SelectMode.SelectError) ? array : null, ref socketTime);
2841  }
2842  else
2843  {
2844  num = UnsafeNclNativeMethods.OSSOCK.select(0, (mode == SelectMode.SelectRead) ? array : null, (mode == SelectMode.SelectWrite) ? array : null, (mode == SelectMode.SelectError) ? array : null, IntPtr.Zero);
2845  }
2846  if (num == -1)
2847  {
2848  SocketException ex = new SocketException();
2849  UpdateStatusAfterSocketError(ex);
2850  if (s_LoggingEnabled)
2851  {
2852  Logging.Exception(Logging.Sockets, this, "Poll", ex);
2853  }
2854  throw ex;
2855  }
2856  if ((int)array[0] == 0)
2857  {
2858  return false;
2859  }
2860  return array[1] == intPtr;
2861  }
2862 
2870  public static void Select(IList checkRead, IList checkWrite, IList checkError, int microSeconds)
2871  {
2872  if ((checkRead == null || checkRead.Count == 0) && (checkWrite == null || checkWrite.Count == 0) && (checkError == null || checkError.Count == 0))
2873  {
2874  throw new ArgumentNullException(SR.GetString("net_sockets_empty_select"));
2875  }
2876  if (checkRead != null && checkRead.Count > 65536)
2877  {
2878  throw new ArgumentOutOfRangeException("checkRead", SR.GetString("net_sockets_toolarge_select", "checkRead", 65536.ToString(NumberFormatInfo.CurrentInfo)));
2879  }
2880  if (checkWrite != null && checkWrite.Count > 65536)
2881  {
2882  throw new ArgumentOutOfRangeException("checkWrite", SR.GetString("net_sockets_toolarge_select", "checkWrite", 65536.ToString(NumberFormatInfo.CurrentInfo)));
2883  }
2884  if (checkError != null && checkError.Count > 65536)
2885  {
2886  throw new ArgumentOutOfRangeException("checkError", SR.GetString("net_sockets_toolarge_select", "checkError", 65536.ToString(NumberFormatInfo.CurrentInfo)));
2887  }
2888  IntPtr[] array = SocketListToFileDescriptorSet(checkRead);
2889  IntPtr[] array2 = SocketListToFileDescriptorSet(checkWrite);
2890  IntPtr[] array3 = SocketListToFileDescriptorSet(checkError);
2891  int num;
2892  if (microSeconds != -1)
2893  {
2894  TimeValue socketTime = default(TimeValue);
2895  MicrosecondsToTimeValue((uint)microSeconds, ref socketTime);
2896  num = UnsafeNclNativeMethods.OSSOCK.select(0, array, array2, array3, ref socketTime);
2897  }
2898  else
2899  {
2900  num = UnsafeNclNativeMethods.OSSOCK.select(0, array, array2, array3, IntPtr.Zero);
2901  }
2902  if (num == -1)
2903  {
2904  throw new SocketException();
2905  }
2906  SelectFileDescriptor(checkRead, array);
2907  SelectFileDescriptor(checkWrite, array2);
2908  SelectFileDescriptor(checkError, array3);
2909  }
2910 
2920  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2921  public IAsyncResult BeginSendFile(string fileName, AsyncCallback callback, object state)
2922  {
2923  return BeginSendFile(fileName, null, null, TransmitFileOptions.UseDefaultWorkerThread, callback, state);
2924  }
2925 
2937  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
2938  public IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
2939  {
2940  if (s_LoggingEnabled)
2941  {
2942  Logging.Enter(Logging.Sockets, this, "BeginConnect", remoteEP);
2943  }
2944  if (CleanedUp)
2945  {
2946  throw new ObjectDisposedException(GetType().FullName);
2947  }
2948  if (remoteEP == null)
2949  {
2950  throw new ArgumentNullException("remoteEP");
2951  }
2952  if (isListening)
2953  {
2954  throw new InvalidOperationException(SR.GetString("net_sockets_mustnotlisten"));
2955  }
2956  DnsEndPoint dnsEndPoint = remoteEP as DnsEndPoint;
2957  if (dnsEndPoint != null)
2958  {
2959  if (dnsEndPoint.AddressFamily != 0 && !CanTryAddressFamily(dnsEndPoint.AddressFamily))
2960  {
2961  throw new NotSupportedException(SR.GetString("net_invalidversion"));
2962  }
2963  return BeginConnect(dnsEndPoint.Host, dnsEndPoint.Port, callback, state);
2964  }
2965  if (CanUseConnectEx(remoteEP))
2966  {
2967  return BeginConnectEx(remoteEP, flowContext: true, callback, state);
2968  }
2969  EndPoint remoteEP2 = remoteEP;
2970  SocketAddress socketAddress = CheckCacheRemote(ref remoteEP2, isOverwrite: true);
2971  ConnectAsyncResult connectAsyncResult = new ConnectAsyncResult(this, remoteEP2, state, callback);
2972  connectAsyncResult.StartPostingAsyncOp(lockCapture: false);
2973  DoBeginConnect(remoteEP2, socketAddress, connectAsyncResult);
2974  connectAsyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
2975  if (s_LoggingEnabled)
2976  {
2977  Logging.Exit(Logging.Sockets, this, "BeginConnect", connectAsyncResult);
2978  }
2979  return connectAsyncResult;
2980  }
2981 
2987  public unsafe SocketInformation DuplicateAndClose(int targetProcessId)
2988  {
2989  if (s_LoggingEnabled)
2990  {
2991  Logging.Enter(Logging.Sockets, this, "DuplicateAndClose", null);
2992  }
2993  if (CleanedUp)
2994  {
2995  throw new ObjectDisposedException(GetType().FullName);
2996  }
2997  ExceptionHelper.UnrestrictedSocketPermission.Demand();
2998  SocketInformation result = default(SocketInformation);
2999  result.ProtocolInformation = new byte[protocolInformationSize];
3000  byte[] protocolInformation = result.ProtocolInformation;
3001  SocketError socketError;
3002  fixed (byte* pinnedBuffer = protocolInformation)
3003  {
3004  socketError = (SocketError)UnsafeNclNativeMethods.OSSOCK.WSADuplicateSocket(m_Handle, (uint)targetProcessId, pinnedBuffer);
3005  }
3006  if (socketError != 0)
3007  {
3008  SocketException ex = new SocketException();
3009  if (s_LoggingEnabled)
3010  {
3011  Logging.Exception(Logging.Sockets, this, "DuplicateAndClose", ex);
3012  }
3013  throw ex;
3014  }
3015  result.IsConnected = Connected;
3016  result.IsNonBlocking = !Blocking;
3017  result.IsListening = isListening;
3018  result.UseOnlyOverlappedIO = UseOnlyOverlappedIO;
3019  result.RemoteEndPoint = m_RemoteEndPoint;
3020  Close(-1);
3021  if (s_LoggingEnabled)
3022  {
3023  Logging.Exit(Logging.Sockets, this, "DuplicateAndClose", null);
3024  }
3025  return result;
3026  }
3027 
3028  internal IAsyncResult UnsafeBeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
3029  {
3030  if (CanUseConnectEx(remoteEP))
3031  {
3032  return BeginConnectEx(remoteEP, flowContext: false, callback, state);
3033  }
3034  EndPoint remoteEP2 = remoteEP;
3035  SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP2);
3036  ConnectAsyncResult connectAsyncResult = new ConnectAsyncResult(this, remoteEP2, state, callback);
3037  DoBeginConnect(remoteEP2, socketAddress, connectAsyncResult);
3038  return connectAsyncResult;
3039  }
3040 
3041  private void DoBeginConnect(EndPoint endPointSnapshot, SocketAddress socketAddress, LazyAsyncResult asyncResult)
3042  {
3043  EndPoint rightEndPoint = m_RightEndPoint;
3044  if (m_AcceptQueueOrConnectResult != null)
3045  {
3046  throw new InvalidOperationException(SR.GetString("net_sockets_no_duplicate_async"));
3047  }
3048  m_AcceptQueueOrConnectResult = asyncResult;
3049  if (!SetAsyncEventSelect(AsyncEventBits.FdConnect))
3050  {
3051  m_AcceptQueueOrConnectResult = null;
3052  throw new ObjectDisposedException(GetType().FullName);
3053  }
3054  IntPtr socketHandle = m_Handle.DangerousGetHandle();
3055  if (m_RightEndPoint == null)
3056  {
3057  m_RightEndPoint = endPointSnapshot;
3058  }
3059  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.WSAConnect(socketHandle, socketAddress.m_Buffer, socketAddress.m_Size, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
3060  if (socketError != 0)
3061  {
3062  socketError = (SocketError)Marshal.GetLastWin32Error();
3063  }
3064  if (socketError == SocketError.WouldBlock)
3065  {
3066  return;
3067  }
3068  bool flag = true;
3069  if (socketError == SocketError.Success)
3070  {
3071  SetToConnected();
3072  }
3073  else
3074  {
3075  asyncResult.ErrorCode = (int)socketError;
3076  }
3077  if (Interlocked.Exchange(ref m_RegisteredWait, null) == null)
3078  {
3079  flag = false;
3080  }
3081  UnsetAsyncEventSelect();
3082  if (socketError == SocketError.Success)
3083  {
3084  if (flag)
3085  {
3086  asyncResult.InvokeCallback();
3087  }
3088  return;
3089  }
3090  m_RightEndPoint = rightEndPoint;
3091  SocketException ex = new SocketException(socketError);
3092  UpdateStatusAfterSocketError(ex);
3093  m_AcceptQueueOrConnectResult = null;
3094  if (s_LoggingEnabled)
3095  {
3096  Logging.Exception(Logging.Sockets, this, "BeginConnect", ex);
3097  }
3098  throw ex;
3099  }
3100 
3101  private bool CanUseConnectEx(EndPoint remoteEP)
3102  {
3103  if (socketType == SocketType.Stream && (m_RightEndPoint != null || remoteEP.GetType() == typeof(IPEndPoint)))
3104  {
3105  if (!Thread.CurrentThread.IsThreadPoolThread && !SettingsSectionInternal.Section.AlwaysUseCompletionPortsForConnect)
3106  {
3107  return m_IsDisconnected;
3108  }
3109  return true;
3110  }
3111  return false;
3112  }
3113 
3114  private void ConnectCallback()
3115  {
3116  LazyAsyncResult lazyAsyncResult = (LazyAsyncResult)m_AcceptQueueOrConnectResult;
3117  if (!lazyAsyncResult.InternalPeekCompleted)
3118  {
3119  NetworkEvents networkEvents = default(NetworkEvents);
3120  networkEvents.Events = AsyncEventBits.FdConnect;
3121  SocketError socketError = SocketError.OperationAborted;
3122  object result = null;
3123  try
3124  {
3125  if (!CleanedUp)
3126  {
3127  try
3128  {
3129  socketError = UnsafeNclNativeMethods.OSSOCK.WSAEnumNetworkEvents(m_Handle, m_AsyncEvent.SafeWaitHandle, ref networkEvents);
3130  socketError = (SocketError)((socketError == SocketError.Success) ? networkEvents.ErrorCodes[4] : Marshal.GetLastWin32Error());
3131  UnsetAsyncEventSelect();
3132  }
3133  catch (ObjectDisposedException)
3134  {
3135  socketError = SocketError.OperationAborted;
3136  }
3137  }
3138  if (socketError == SocketError.Success)
3139  {
3140  SetToConnected();
3141  }
3142  }
3143  catch (Exception ex2)
3144  {
3145  if (NclUtilities.IsFatal(ex2))
3146  {
3147  throw;
3148  }
3149  result = ex2;
3150  }
3151  if (!lazyAsyncResult.InternalPeekCompleted)
3152  {
3153  lazyAsyncResult.ErrorCode = (int)socketError;
3154  lazyAsyncResult.InvokeCallback(result);
3155  }
3156  }
3157  }
3158 
3171  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3172  public IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
3173  {
3174  if (s_LoggingEnabled)
3175  {
3176  Logging.Enter(Logging.Sockets, this, "BeginConnect", host);
3177  }
3178  if (CleanedUp)
3179  {
3180  throw new ObjectDisposedException(GetType().FullName);
3181  }
3182  if (host == null)
3183  {
3184  throw new ArgumentNullException("host");
3185  }
3186  if (!ValidationHelper.ValidateTcpPort(port))
3187  {
3188  throw new ArgumentOutOfRangeException("port");
3189  }
3190  if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6)
3191  {
3192  throw new NotSupportedException(SR.GetString("net_invalidversion"));
3193  }
3194  if (isListening)
3195  {
3196  throw new InvalidOperationException(SR.GetString("net_sockets_mustnotlisten"));
3197  }
3198  MultipleAddressConnectAsyncResult multipleAddressConnectAsyncResult = new MultipleAddressConnectAsyncResult(null, port, this, state, requestCallback);
3199  multipleAddressConnectAsyncResult.StartPostingAsyncOp(lockCapture: false);
3200  IAsyncResult asyncResult = Dns.UnsafeBeginGetHostAddresses(host, DnsCallback, multipleAddressConnectAsyncResult);
3201  if (asyncResult.CompletedSynchronously && DoDnsCallback(asyncResult, multipleAddressConnectAsyncResult))
3202  {
3203  multipleAddressConnectAsyncResult.InvokeCallback();
3204  }
3205  multipleAddressConnectAsyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
3206  if (s_LoggingEnabled)
3207  {
3208  Logging.Exit(Logging.Sockets, this, "BeginConnect", multipleAddressConnectAsyncResult);
3209  }
3210  return multipleAddressConnectAsyncResult;
3211  }
3212 
3227  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3228  public IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
3229  {
3230  if (s_LoggingEnabled)
3231  {
3232  Logging.Enter(Logging.Sockets, this, "BeginConnect", address);
3233  }
3234  if (CleanedUp)
3235  {
3236  throw new ObjectDisposedException(GetType().FullName);
3237  }
3238  if (address == null)
3239  {
3240  throw new ArgumentNullException("address");
3241  }
3242  if (!ValidationHelper.ValidateTcpPort(port))
3243  {
3244  throw new ArgumentOutOfRangeException("port");
3245  }
3246  if (!CanTryAddressFamily(address.AddressFamily))
3247  {
3248  throw new NotSupportedException(SR.GetString("net_invalidversion"));
3249  }
3250  IAsyncResult asyncResult = BeginConnect(new IPEndPoint(address, port), requestCallback, state);
3251  if (s_LoggingEnabled)
3252  {
3253  Logging.Exit(Logging.Sockets, this, "BeginConnect", asyncResult);
3254  }
3255  return asyncResult;
3256  }
3257 
3272  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3273  public IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
3274  {
3275  if (s_LoggingEnabled)
3276  {
3277  Logging.Enter(Logging.Sockets, this, "BeginConnect", addresses);
3278  }
3279  if (CleanedUp)
3280  {
3281  throw new ObjectDisposedException(GetType().FullName);
3282  }
3283  if (addresses == null)
3284  {
3285  throw new ArgumentNullException("addresses");
3286  }
3287  if (addresses.Length == 0)
3288  {
3289  throw new ArgumentException(SR.GetString("net_invalidAddressList"), "addresses");
3290  }
3291  if (!ValidationHelper.ValidateTcpPort(port))
3292  {
3293  throw new ArgumentOutOfRangeException("port");
3294  }
3295  if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6)
3296  {
3297  throw new NotSupportedException(SR.GetString("net_invalidversion"));
3298  }
3299  if (isListening)
3300  {
3301  throw new InvalidOperationException(SR.GetString("net_sockets_mustnotlisten"));
3302  }
3303  MultipleAddressConnectAsyncResult multipleAddressConnectAsyncResult = new MultipleAddressConnectAsyncResult(addresses, port, this, state, requestCallback);
3304  multipleAddressConnectAsyncResult.StartPostingAsyncOp(lockCapture: false);
3305  if (DoMultipleAddressConnectCallback(PostOneBeginConnect(multipleAddressConnectAsyncResult), multipleAddressConnectAsyncResult))
3306  {
3307  multipleAddressConnectAsyncResult.InvokeCallback();
3308  }
3309  multipleAddressConnectAsyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
3310  if (s_LoggingEnabled)
3311  {
3312  Logging.Exit(Logging.Sockets, this, "BeginConnect", multipleAddressConnectAsyncResult);
3313  }
3314  return multipleAddressConnectAsyncResult;
3315  }
3316 
3326  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3327  public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state)
3328  {
3329  DisconnectOverlappedAsyncResult disconnectOverlappedAsyncResult = new DisconnectOverlappedAsyncResult(this, state, callback);
3330  disconnectOverlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
3331  DoBeginDisconnect(reuseSocket, disconnectOverlappedAsyncResult);
3332  disconnectOverlappedAsyncResult.FinishPostingAsyncOp();
3333  return disconnectOverlappedAsyncResult;
3334  }
3335 
3336  private void DoBeginDisconnect(bool reuseSocket, DisconnectOverlappedAsyncResult asyncResult)
3337  {
3338  if (s_LoggingEnabled)
3339  {
3340  Logging.Enter(Logging.Sockets, this, "BeginDisconnect", null);
3341  }
3342  if (CleanedUp)
3343  {
3344  throw new ObjectDisposedException(GetType().FullName);
3345  }
3346  asyncResult.SetUnmanagedStructures(null);
3347  SocketError socketError = SocketError.Success;
3348  if (!DisconnectEx(m_Handle, asyncResult.OverlappedHandle, reuseSocket ? 2 : 0, 0))
3349  {
3350  socketError = (SocketError)Marshal.GetLastWin32Error();
3351  }
3352  if (socketError == SocketError.Success)
3353  {
3354  SetToDisconnected();
3355  m_RemoteEndPoint = null;
3356  }
3357  socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
3358  if (socketError != 0)
3359  {
3360  SocketException ex = new SocketException(socketError);
3361  UpdateStatusAfterSocketError(ex);
3362  if (s_LoggingEnabled)
3363  {
3364  Logging.Exception(Logging.Sockets, this, "BeginDisconnect", ex);
3365  }
3366  throw ex;
3367  }
3368  if (s_LoggingEnabled)
3369  {
3370  Logging.Exit(Logging.Sockets, this, "BeginDisconnect", asyncResult);
3371  }
3372  }
3373 
3380  public void Disconnect(bool reuseSocket)
3381  {
3382  if (s_LoggingEnabled)
3383  {
3384  Logging.Enter(Logging.Sockets, this, "Disconnect", null);
3385  }
3386  if (CleanedUp)
3387  {
3388  throw new ObjectDisposedException(GetType().FullName);
3389  }
3390  SocketError socketError = SocketError.Success;
3391  if (!DisconnectEx_Blocking(m_Handle.DangerousGetHandle(), IntPtr.Zero, reuseSocket ? 2 : 0, 0))
3392  {
3393  socketError = (SocketError)Marshal.GetLastWin32Error();
3394  }
3395  if (socketError != 0)
3396  {
3397  SocketException ex = new SocketException(socketError);
3398  UpdateStatusAfterSocketError(ex);
3399  if (s_LoggingEnabled)
3400  {
3401  Logging.Exception(Logging.Sockets, this, "Disconnect", ex);
3402  }
3403  throw ex;
3404  }
3405  SetToDisconnected();
3406  m_RemoteEndPoint = null;
3407  if (s_LoggingEnabled)
3408  {
3409  Logging.Exit(Logging.Sockets, this, "Disconnect", null);
3410  }
3411  }
3412 
3423  public void EndConnect(IAsyncResult asyncResult)
3424  {
3425  if (s_LoggingEnabled)
3426  {
3427  Logging.Enter(Logging.Sockets, this, "EndConnect", asyncResult);
3428  }
3429  if (CleanedUp)
3430  {
3431  throw new ObjectDisposedException(GetType().FullName);
3432  }
3433  if (asyncResult == null)
3434  {
3435  throw new ArgumentNullException("asyncResult");
3436  }
3437  LazyAsyncResult lazyAsyncResult = null;
3438  EndPoint endPoint = null;
3439  ConnectOverlappedAsyncResult connectOverlappedAsyncResult = asyncResult as ConnectOverlappedAsyncResult;
3440  if (connectOverlappedAsyncResult == null)
3441  {
3442  MultipleAddressConnectAsyncResult multipleAddressConnectAsyncResult = asyncResult as MultipleAddressConnectAsyncResult;
3443  if (multipleAddressConnectAsyncResult == null)
3444  {
3445  ConnectAsyncResult connectAsyncResult = asyncResult as ConnectAsyncResult;
3446  if (connectAsyncResult != null)
3447  {
3448  endPoint = connectAsyncResult.RemoteEndPoint;
3449  lazyAsyncResult = connectAsyncResult;
3450  }
3451  }
3452  else
3453  {
3454  endPoint = multipleAddressConnectAsyncResult.RemoteEndPoint;
3455  lazyAsyncResult = multipleAddressConnectAsyncResult;
3456  }
3457  }
3458  else
3459  {
3460  endPoint = connectOverlappedAsyncResult.RemoteEndPoint;
3461  lazyAsyncResult = connectOverlappedAsyncResult;
3462  }
3463  if (lazyAsyncResult == null || lazyAsyncResult.AsyncObject != this)
3464  {
3465  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
3466  }
3467  if (lazyAsyncResult.EndCalled)
3468  {
3469  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndConnect"));
3470  }
3471  lazyAsyncResult.InternalWaitForCompletion();
3472  lazyAsyncResult.EndCalled = true;
3473  m_AcceptQueueOrConnectResult = null;
3474  if (lazyAsyncResult.Result is Exception)
3475  {
3476  if (s_LoggingEnabled)
3477  {
3478  Logging.Exception(Logging.Sockets, this, "EndConnect", (Exception)lazyAsyncResult.Result);
3479  }
3480  throw (Exception)lazyAsyncResult.Result;
3481  }
3482  if (lazyAsyncResult.ErrorCode != 0)
3483  {
3484  SocketException ex = new SocketException(lazyAsyncResult.ErrorCode, endPoint);
3485  UpdateStatusAfterSocketError(ex);
3486  if (s_LoggingEnabled)
3487  {
3488  Logging.Exception(Logging.Sockets, this, "EndConnect", ex);
3489  }
3490  throw ex;
3491  }
3492  if (s_LoggingEnabled)
3493  {
3494  Logging.PrintInfo(Logging.Sockets, this, SR.GetString("net_log_socket_connected", LocalEndPoint, RemoteEndPoint));
3495  Logging.Exit(Logging.Sockets, this, "EndConnect", "");
3496  }
3497  }
3498 
3511  public void EndDisconnect(IAsyncResult asyncResult)
3512  {
3513  if (s_LoggingEnabled)
3514  {
3515  Logging.Enter(Logging.Sockets, this, "EndDisconnect", asyncResult);
3516  }
3517  if (CleanedUp)
3518  {
3519  throw new ObjectDisposedException(GetType().FullName);
3520  }
3521  if (asyncResult == null)
3522  {
3523  throw new ArgumentNullException("asyncResult");
3524  }
3525  LazyAsyncResult lazyAsyncResult = asyncResult as LazyAsyncResult;
3526  if (lazyAsyncResult == null || lazyAsyncResult.AsyncObject != this)
3527  {
3528  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
3529  }
3530  if (lazyAsyncResult.EndCalled)
3531  {
3532  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndDisconnect"));
3533  }
3534  lazyAsyncResult.InternalWaitForCompletion();
3535  lazyAsyncResult.EndCalled = true;
3536  if (lazyAsyncResult.ErrorCode != 0)
3537  {
3538  SocketException ex = new SocketException(lazyAsyncResult.ErrorCode);
3539  UpdateStatusAfterSocketError(ex);
3540  if (s_LoggingEnabled)
3541  {
3542  Logging.Exception(Logging.Sockets, this, "EndDisconnect", ex);
3543  }
3544  throw ex;
3545  }
3546  if (s_LoggingEnabled)
3547  {
3548  Logging.Exit(Logging.Sockets, this, "EndDisconnect", null);
3549  }
3550  }
3551 
3569  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3570  public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
3571  {
3572  SocketError errorCode;
3573  IAsyncResult result = BeginSend(buffer, offset, size, socketFlags, out errorCode, callback, state);
3574  if (errorCode != 0 && errorCode != SocketError.IOPending)
3575  {
3576  throw new SocketException(errorCode);
3577  }
3578  return result;
3579  }
3580 
3599  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3600  public IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
3601  {
3602  if (s_LoggingEnabled)
3603  {
3604  Logging.Enter(Logging.Sockets, this, "BeginSend", "");
3605  }
3606  if (CleanedUp)
3607  {
3608  throw new ObjectDisposedException(GetType().FullName);
3609  }
3610  if (buffer == null)
3611  {
3612  throw new ArgumentNullException("buffer");
3613  }
3614  if (offset < 0 || offset > buffer.Length)
3615  {
3616  throw new ArgumentOutOfRangeException("offset");
3617  }
3618  if (size < 0 || size > buffer.Length - offset)
3619  {
3620  throw new ArgumentOutOfRangeException("size");
3621  }
3622  OverlappedAsyncResult overlappedAsyncResult = new OverlappedAsyncResult(this, state, callback);
3623  overlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
3624  errorCode = DoBeginSend(buffer, offset, size, socketFlags, overlappedAsyncResult);
3625  if (errorCode != 0 && errorCode != SocketError.IOPending)
3626  {
3627  overlappedAsyncResult = null;
3628  }
3629  else
3630  {
3631  overlappedAsyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
3632  }
3633  if (s_LoggingEnabled)
3634  {
3635  Logging.Exit(Logging.Sockets, this, "BeginSend", overlappedAsyncResult);
3636  }
3637  return overlappedAsyncResult;
3638  }
3639 
3640  internal IAsyncResult UnsafeBeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
3641  {
3642  if (s_LoggingEnabled)
3643  {
3644  Logging.Enter(Logging.Sockets, this, "UnsafeBeginSend", "");
3645  }
3646  if (CleanedUp)
3647  {
3648  throw new ObjectDisposedException(GetType().FullName);
3649  }
3650  OverlappedAsyncResult overlappedAsyncResult = new OverlappedAsyncResult(this, state, callback);
3651  SocketError socketError = DoBeginSend(buffer, offset, size, socketFlags, overlappedAsyncResult);
3652  if (socketError != 0 && socketError != SocketError.IOPending)
3653  {
3654  throw new SocketException(socketError);
3655  }
3656  if (s_LoggingEnabled)
3657  {
3658  Logging.Exit(Logging.Sockets, this, "UnsafeBeginSend", overlappedAsyncResult);
3659  }
3660  return overlappedAsyncResult;
3661  }
3662 
3663  private SocketError DoBeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
3664  {
3665  SocketError socketError = SocketError.SocketError;
3666  try
3667  {
3668  asyncResult.SetUnmanagedStructures(buffer, offset, size, null, pinSocketAddress: false, ref Caches.SendOverlappedCache);
3669  socketError = UnsafeNclNativeMethods.OSSOCK.WSASend(m_Handle, ref asyncResult.m_SingleBuffer, 1, out int _, socketFlags, asyncResult.OverlappedHandle, IntPtr.Zero);
3670  if (socketError != 0)
3671  {
3672  socketError = (SocketError)Marshal.GetLastWin32Error();
3673  }
3674  }
3675  finally
3676  {
3677  socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
3678  }
3679  if (socketError != 0)
3680  {
3681  asyncResult.ExtractCache(ref Caches.SendOverlappedCache);
3682  UpdateStatusAfterSocketError(socketError);
3683  if (s_LoggingEnabled)
3684  {
3685  Logging.Exception(Logging.Sockets, this, "BeginSend", new SocketException(socketError));
3686  }
3687  }
3688  return socketError;
3689  }
3690 
3703  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3704  public IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
3705  {
3706  TransmitFileOverlappedAsyncResult transmitFileOverlappedAsyncResult = new TransmitFileOverlappedAsyncResult(this, state, callback);
3707  transmitFileOverlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
3708  DoBeginSendFile(fileName, preBuffer, postBuffer, flags, transmitFileOverlappedAsyncResult);
3709  transmitFileOverlappedAsyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
3710  return transmitFileOverlappedAsyncResult;
3711  }
3712 
3713  private void DoBeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, TransmitFileOverlappedAsyncResult asyncResult)
3714  {
3715  if (s_LoggingEnabled)
3716  {
3717  Logging.Enter(Logging.Sockets, this, "BeginSendFile", "");
3718  }
3719  if (CleanedUp)
3720  {
3721  throw new ObjectDisposedException(GetType().FullName);
3722  }
3723  if (CleanedUp)
3724  {
3725  throw new ObjectDisposedException(GetType().FullName);
3726  }
3727  if (!Connected)
3728  {
3729  throw new NotSupportedException(SR.GetString("net_notconnected"));
3730  }
3731  FileStream fileStream = null;
3732  if (fileName != null && fileName.Length > 0)
3733  {
3734  fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
3735  }
3736  SafeHandle safeHandle = null;
3737  if (fileStream != null)
3738  {
3739  ExceptionHelper.UnmanagedPermission.Assert();
3740  try
3741  {
3742  safeHandle = fileStream.SafeFileHandle;
3743  }
3744  finally
3745  {
3747  }
3748  }
3749  SocketError errorCode = SocketError.SocketError;
3750  try
3751  {
3752  asyncResult.SetUnmanagedStructures(preBuffer, postBuffer, fileStream, flags, ref Caches.SendOverlappedCache);
3753  bool flag = false;
3754  flag = ((safeHandle == null) ? UnsafeNclNativeMethods.OSSOCK.TransmitFile2(m_Handle, IntPtr.Zero, 0, 0, asyncResult.OverlappedHandle, asyncResult.TransmitFileBuffers, flags) : UnsafeNclNativeMethods.OSSOCK.TransmitFile(m_Handle, safeHandle, 0, 0, asyncResult.OverlappedHandle, asyncResult.TransmitFileBuffers, flags));
3755  errorCode = (SocketError)((!flag) ? Marshal.GetLastWin32Error() : 0);
3756  }
3757  finally
3758  {
3759  errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode);
3760  }
3761  if (errorCode != 0)
3762  {
3763  asyncResult.ExtractCache(ref Caches.SendOverlappedCache);
3764  SocketException ex = new SocketException(errorCode);
3765  UpdateStatusAfterSocketError(ex);
3766  if (s_LoggingEnabled)
3767  {
3768  Logging.Exception(Logging.Sockets, this, "BeginSendFile", ex);
3769  }
3770  throw ex;
3771  }
3772  if (s_LoggingEnabled)
3773  {
3774  Logging.Exit(Logging.Sockets, this, "BeginSendFile", errorCode);
3775  }
3776  }
3777 
3790  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3791  public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
3792  {
3793  SocketError errorCode;
3794  IAsyncResult result = BeginSend(buffers, socketFlags, out errorCode, callback, state);
3795  if (errorCode != 0 && errorCode != SocketError.IOPending)
3796  {
3797  throw new SocketException(errorCode);
3798  }
3799  return result;
3800  }
3801 
3815  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
3816  public IAsyncResult BeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
3817  {
3818  if (s_LoggingEnabled)
3819  {
3820  Logging.Enter(Logging.Sockets, this, "BeginSend", "");
3821  }
3822  if (CleanedUp)
3823  {
3824  throw new ObjectDisposedException(GetType().FullName);
3825  }
3826  if (buffers == null)
3827  {
3828  throw new ArgumentNullException("buffers");
3829  }
3830  if (buffers.Count == 0)
3831  {
3832  throw new ArgumentException(SR.GetString("net_sockets_zerolist", "buffers"), "buffers");
3833  }
3834  OverlappedAsyncResult overlappedAsyncResult = new OverlappedAsyncResult(this, state, callback);
3835  overlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
3836  errorCode = DoBeginSend(buffers, socketFlags, overlappedAsyncResult);
3837  overlappedAsyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
3838  if (errorCode != 0 && errorCode != SocketError.IOPending)
3839  {
3840  overlappedAsyncResult = null;
3841  }
3842  if (s_LoggingEnabled)
3843  {
3844  Logging.Exit(Logging.Sockets, this, "BeginSend", overlappedAsyncResult);
3845  }
3846  return overlappedAsyncResult;
3847  }
3848 
3849  private SocketError DoBeginSend(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
3850  {
3851  SocketError socketError = SocketError.SocketError;
3852  try
3853  {
3854  asyncResult.SetUnmanagedStructures(buffers, ref Caches.SendOverlappedCache);
3855  socketError = UnsafeNclNativeMethods.OSSOCK.WSASend(m_Handle, asyncResult.m_WSABuffers, asyncResult.m_WSABuffers.Length, out int _, socketFlags, asyncResult.OverlappedHandle, IntPtr.Zero);
3856  if (socketError != 0)
3857  {
3858  socketError = (SocketError)Marshal.GetLastWin32Error();
3859  }
3860  }
3861  finally
3862  {
3863  socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
3864  }
3865  if (socketError != 0)
3866  {
3867  asyncResult.ExtractCache(ref Caches.SendOverlappedCache);
3868  UpdateStatusAfterSocketError(socketError);
3869  if (s_LoggingEnabled)
3870  {
3871  Logging.Exception(Logging.Sockets, this, "BeginSend", new SocketException(socketError));
3872  }
3873  }
3874  return socketError;
3875  }
3876 
3888  public int EndSend(IAsyncResult asyncResult)
3889  {
3890  SocketError errorCode;
3891  int result = EndSend(asyncResult, out errorCode);
3892  if (errorCode != 0)
3893  {
3894  throw new SocketException(errorCode);
3895  }
3896  return result;
3897  }
3898 
3911  public int EndSend(IAsyncResult asyncResult, out SocketError errorCode)
3912  {
3913  if (s_LoggingEnabled)
3914  {
3915  Logging.Enter(Logging.Sockets, this, "EndSend", asyncResult);
3916  }
3917  if (CleanedUp)
3918  {
3919  throw new ObjectDisposedException(GetType().FullName);
3920  }
3921  if (asyncResult == null)
3922  {
3923  throw new ArgumentNullException("asyncResult");
3924  }
3925  OverlappedAsyncResult overlappedAsyncResult = asyncResult as OverlappedAsyncResult;
3926  if (overlappedAsyncResult == null || overlappedAsyncResult.AsyncObject != this)
3927  {
3928  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
3929  }
3930  if (overlappedAsyncResult.EndCalled)
3931  {
3932  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndSend"));
3933  }
3934  int num = (int)overlappedAsyncResult.InternalWaitForCompletion();
3935  overlappedAsyncResult.EndCalled = true;
3936  overlappedAsyncResult.ExtractCache(ref Caches.SendOverlappedCache);
3937  if (s_PerfCountersEnabled && num > 0)
3938  {
3939  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, num);
3940  if (Transport == TransportType.Udp)
3941  {
3942  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
3943  }
3944  }
3945  errorCode = (SocketError)overlappedAsyncResult.ErrorCode;
3946  if (errorCode != 0)
3947  {
3948  UpdateStatusAfterSocketError(errorCode);
3949  if (s_LoggingEnabled)
3950  {
3951  Logging.Exception(Logging.Sockets, this, "EndSend", new SocketException(errorCode));
3952  Logging.Exit(Logging.Sockets, this, "EndSend", 0);
3953  }
3954  return 0;
3955  }
3956  if (s_LoggingEnabled)
3957  {
3958  Logging.Exit(Logging.Sockets, this, "EndSend", num);
3959  }
3960  return num;
3961  }
3962 
3974  public void EndSendFile(IAsyncResult asyncResult)
3975  {
3976  if (s_LoggingEnabled)
3977  {
3978  Logging.Enter(Logging.Sockets, this, "EndSendFile", asyncResult);
3979  }
3980  if (CleanedUp)
3981  {
3982  throw new ObjectDisposedException(GetType().FullName);
3983  }
3984  if (asyncResult == null)
3985  {
3986  throw new ArgumentNullException("asyncResult");
3987  }
3988  TransmitFileOverlappedAsyncResult transmitFileOverlappedAsyncResult = asyncResult as TransmitFileOverlappedAsyncResult;
3989  if (transmitFileOverlappedAsyncResult == null || transmitFileOverlappedAsyncResult.AsyncObject != this)
3990  {
3991  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
3992  }
3993  if (transmitFileOverlappedAsyncResult.EndCalled)
3994  {
3995  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndSendFile"));
3996  }
3997  transmitFileOverlappedAsyncResult.InternalWaitForCompletion();
3998  transmitFileOverlappedAsyncResult.EndCalled = true;
3999  transmitFileOverlappedAsyncResult.ExtractCache(ref Caches.SendOverlappedCache);
4000  if ((transmitFileOverlappedAsyncResult.Flags & (TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket)) != 0)
4001  {
4002  SetToDisconnected();
4003  m_RemoteEndPoint = null;
4004  }
4005  if (transmitFileOverlappedAsyncResult.ErrorCode != 0)
4006  {
4007  SocketException ex = new SocketException(transmitFileOverlappedAsyncResult.ErrorCode);
4008  UpdateStatusAfterSocketError(ex);
4009  if (s_LoggingEnabled)
4010  {
4011  Logging.Exception(Logging.Sockets, this, "EndSendFile", ex);
4012  }
4013  throw ex;
4014  }
4015  if (s_LoggingEnabled)
4016  {
4017  Logging.Exit(Logging.Sockets, this, "EndSendFile", "");
4018  }
4019  }
4020 
4041  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
4042  public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state)
4043  {
4044  if (s_LoggingEnabled)
4045  {
4046  Logging.Enter(Logging.Sockets, this, "BeginSendTo", "");
4047  }
4048  if (CleanedUp)
4049  {
4050  throw new ObjectDisposedException(GetType().FullName);
4051  }
4052  if (buffer == null)
4053  {
4054  throw new ArgumentNullException("buffer");
4055  }
4056  if (remoteEP == null)
4057  {
4058  throw new ArgumentNullException("remoteEP");
4059  }
4060  if (offset < 0 || offset > buffer.Length)
4061  {
4062  throw new ArgumentOutOfRangeException("offset");
4063  }
4064  if (size < 0 || size > buffer.Length - offset)
4065  {
4066  throw new ArgumentOutOfRangeException("size");
4067  }
4068  EndPoint remoteEP2 = remoteEP;
4069  SocketAddress socketAddress = CheckCacheRemote(ref remoteEP2, isOverwrite: false);
4070  OverlappedAsyncResult overlappedAsyncResult = new OverlappedAsyncResult(this, state, callback);
4071  overlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
4072  DoBeginSendTo(buffer, offset, size, socketFlags, remoteEP2, socketAddress, overlappedAsyncResult);
4073  overlappedAsyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
4074  if (s_LoggingEnabled)
4075  {
4076  Logging.Exit(Logging.Sockets, this, "BeginSendTo", overlappedAsyncResult);
4077  }
4078  return overlappedAsyncResult;
4079  }
4080 
4081  private void DoBeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint endPointSnapshot, SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
4082  {
4083  EndPoint rightEndPoint = m_RightEndPoint;
4084  SocketError socketError = SocketError.SocketError;
4085  try
4086  {
4087  asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, pinSocketAddress: false, ref Caches.SendOverlappedCache);
4088  if (m_RightEndPoint == null)
4089  {
4090  m_RightEndPoint = endPointSnapshot;
4091  }
4092  socketError = UnsafeNclNativeMethods.OSSOCK.WSASendTo(m_Handle, ref asyncResult.m_SingleBuffer, 1, out int _, socketFlags, asyncResult.GetSocketAddressPtr(), asyncResult.SocketAddress.Size, asyncResult.OverlappedHandle, IntPtr.Zero);
4093  if (socketError != 0)
4094  {
4095  socketError = (SocketError)Marshal.GetLastWin32Error();
4096  }
4097  }
4098  catch (ObjectDisposedException)
4099  {
4100  m_RightEndPoint = rightEndPoint;
4101  throw;
4102  }
4103  finally
4104  {
4105  socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
4106  }
4107  if (socketError != 0)
4108  {
4109  m_RightEndPoint = rightEndPoint;
4110  asyncResult.ExtractCache(ref Caches.SendOverlappedCache);
4111  SocketException ex2 = new SocketException(socketError);
4112  UpdateStatusAfterSocketError(ex2);
4113  if (s_LoggingEnabled)
4114  {
4115  Logging.Exception(Logging.Sockets, this, "BeginSendTo", ex2);
4116  }
4117  throw ex2;
4118  }
4119  }
4120 
4132  public int EndSendTo(IAsyncResult asyncResult)
4133  {
4134  if (s_LoggingEnabled)
4135  {
4136  Logging.Enter(Logging.Sockets, this, "EndSendTo", asyncResult);
4137  }
4138  if (CleanedUp)
4139  {
4140  throw new ObjectDisposedException(GetType().FullName);
4141  }
4142  if (asyncResult == null)
4143  {
4144  throw new ArgumentNullException("asyncResult");
4145  }
4146  OverlappedAsyncResult overlappedAsyncResult = asyncResult as OverlappedAsyncResult;
4147  if (overlappedAsyncResult == null || overlappedAsyncResult.AsyncObject != this)
4148  {
4149  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
4150  }
4151  if (overlappedAsyncResult.EndCalled)
4152  {
4153  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndSendTo"));
4154  }
4155  int num = (int)overlappedAsyncResult.InternalWaitForCompletion();
4156  overlappedAsyncResult.EndCalled = true;
4157  overlappedAsyncResult.ExtractCache(ref Caches.SendOverlappedCache);
4158  if (s_PerfCountersEnabled && num > 0)
4159  {
4160  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, num);
4161  if (Transport == TransportType.Udp)
4162  {
4163  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
4164  }
4165  }
4166  if (overlappedAsyncResult.ErrorCode != 0)
4167  {
4168  SocketException ex = new SocketException(overlappedAsyncResult.ErrorCode);
4169  UpdateStatusAfterSocketError(ex);
4170  if (s_LoggingEnabled)
4171  {
4172  Logging.Exception(Logging.Sockets, this, "EndSendTo", ex);
4173  }
4174  throw ex;
4175  }
4176  if (s_LoggingEnabled)
4177  {
4178  Logging.Exit(Logging.Sockets, this, "EndSendTo", num);
4179  }
4180  return num;
4181  }
4182 
4201  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
4202  public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
4203  {
4204  SocketError errorCode;
4205  IAsyncResult result = BeginReceive(buffer, offset, size, socketFlags, out errorCode, callback, state);
4206  if (errorCode != 0 && errorCode != SocketError.IOPending)
4207  {
4208  throw new SocketException(errorCode);
4209  }
4210  return result;
4211  }
4212 
4232  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
4233  public IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
4234  {
4235  if (s_LoggingEnabled)
4236  {
4237  Logging.Enter(Logging.Sockets, this, "BeginReceive", "");
4238  }
4239  if (CleanedUp)
4240  {
4241  throw new ObjectDisposedException(GetType().FullName);
4242  }
4243  if (buffer == null)
4244  {
4245  throw new ArgumentNullException("buffer");
4246  }
4247  if (offset < 0 || offset > buffer.Length)
4248  {
4249  throw new ArgumentOutOfRangeException("offset");
4250  }
4251  if (size < 0 || size > buffer.Length - offset)
4252  {
4253  throw new ArgumentOutOfRangeException("size");
4254  }
4255  OverlappedAsyncResult overlappedAsyncResult = new OverlappedAsyncResult(this, state, callback);
4256  overlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
4257  errorCode = DoBeginReceive(buffer, offset, size, socketFlags, overlappedAsyncResult);
4258  if (errorCode != 0 && errorCode != SocketError.IOPending)
4259  {
4260  overlappedAsyncResult = null;
4261  }
4262  else
4263  {
4264  overlappedAsyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
4265  }
4266  if (s_LoggingEnabled)
4267  {
4268  Logging.Exit(Logging.Sockets, this, "BeginReceive", overlappedAsyncResult);
4269  }
4270  return overlappedAsyncResult;
4271  }
4272 
4273  internal IAsyncResult UnsafeBeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
4274  {
4275  if (s_LoggingEnabled)
4276  {
4277  Logging.Enter(Logging.Sockets, this, "UnsafeBeginReceive", "");
4278  }
4279  if (CleanedUp)
4280  {
4281  throw new ObjectDisposedException(GetType().FullName);
4282  }
4283  OverlappedAsyncResult overlappedAsyncResult = new OverlappedAsyncResult(this, state, callback);
4284  DoBeginReceive(buffer, offset, size, socketFlags, overlappedAsyncResult);
4285  if (s_LoggingEnabled)
4286  {
4287  Logging.Exit(Logging.Sockets, this, "UnsafeBeginReceive", overlappedAsyncResult);
4288  }
4289  return overlappedAsyncResult;
4290  }
4291 
4292  private SocketError DoBeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
4293  {
4294  SocketError socketError = SocketError.SocketError;
4295  try
4296  {
4297  asyncResult.SetUnmanagedStructures(buffer, offset, size, null, pinSocketAddress: false, ref Caches.ReceiveOverlappedCache);
4298  socketError = UnsafeNclNativeMethods.OSSOCK.WSARecv(m_Handle, ref asyncResult.m_SingleBuffer, 1, out int _, ref socketFlags, asyncResult.OverlappedHandle, IntPtr.Zero);
4299  if (socketError != 0)
4300  {
4301  socketError = (SocketError)Marshal.GetLastWin32Error();
4302  }
4303  }
4304  finally
4305  {
4306  socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
4307  }
4308  if (socketError != 0)
4309  {
4310  asyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4311  UpdateStatusAfterSocketError(socketError);
4312  if (s_LoggingEnabled)
4313  {
4314  Logging.Exception(Logging.Sockets, this, "BeginReceive", new SocketException(socketError));
4315  }
4316  asyncResult.InvokeCallback(new SocketException(socketError));
4317  }
4318  return socketError;
4319  }
4320 
4332  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
4333  public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
4334  {
4335  SocketError errorCode;
4336  IAsyncResult result = BeginReceive(buffers, socketFlags, out errorCode, callback, state);
4337  if (errorCode != 0 && errorCode != SocketError.IOPending)
4338  {
4339  throw new SocketException(errorCode);
4340  }
4341  return result;
4342  }
4343 
4356  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
4357  public IAsyncResult BeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
4358  {
4359  if (s_LoggingEnabled)
4360  {
4361  Logging.Enter(Logging.Sockets, this, "BeginReceive", "");
4362  }
4363  if (CleanedUp)
4364  {
4365  throw new ObjectDisposedException(GetType().FullName);
4366  }
4367  if (buffers == null)
4368  {
4369  throw new ArgumentNullException("buffers");
4370  }
4371  if (buffers.Count == 0)
4372  {
4373  throw new ArgumentException(SR.GetString("net_sockets_zerolist", "buffers"), "buffers");
4374  }
4375  OverlappedAsyncResult overlappedAsyncResult = new OverlappedAsyncResult(this, state, callback);
4376  overlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
4377  errorCode = DoBeginReceive(buffers, socketFlags, overlappedAsyncResult);
4378  if (errorCode != 0 && errorCode != SocketError.IOPending)
4379  {
4380  overlappedAsyncResult = null;
4381  }
4382  else
4383  {
4384  overlappedAsyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
4385  }
4386  if (s_LoggingEnabled)
4387  {
4388  Logging.Exit(Logging.Sockets, this, "BeginReceive", overlappedAsyncResult);
4389  }
4390  return overlappedAsyncResult;
4391  }
4392 
4393  private SocketError DoBeginReceive(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
4394  {
4395  SocketError socketError = SocketError.SocketError;
4396  try
4397  {
4398  asyncResult.SetUnmanagedStructures(buffers, ref Caches.ReceiveOverlappedCache);
4399  socketError = UnsafeNclNativeMethods.OSSOCK.WSARecv(m_Handle, asyncResult.m_WSABuffers, asyncResult.m_WSABuffers.Length, out int _, ref socketFlags, asyncResult.OverlappedHandle, IntPtr.Zero);
4400  if (socketError != 0)
4401  {
4402  socketError = (SocketError)Marshal.GetLastWin32Error();
4403  }
4404  }
4405  finally
4406  {
4407  socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
4408  }
4409  if (socketError != 0)
4410  {
4411  asyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4412  UpdateStatusAfterSocketError(socketError);
4413  if (s_LoggingEnabled)
4414  {
4415  Logging.Exception(Logging.Sockets, this, "BeginReceive", new SocketException(socketError));
4416  }
4417  }
4418  return socketError;
4419  }
4420 
4432  public int EndReceive(IAsyncResult asyncResult)
4433  {
4434  SocketError errorCode;
4435  int result = EndReceive(asyncResult, out errorCode);
4436  if (errorCode != 0)
4437  {
4438  throw new SocketException(errorCode);
4439  }
4440  return result;
4441  }
4442 
4455  public int EndReceive(IAsyncResult asyncResult, out SocketError errorCode)
4456  {
4457  if (s_LoggingEnabled)
4458  {
4459  Logging.Enter(Logging.Sockets, this, "EndReceive", asyncResult);
4460  }
4461  if (CleanedUp)
4462  {
4463  throw new ObjectDisposedException(GetType().FullName);
4464  }
4465  if (asyncResult == null)
4466  {
4467  throw new ArgumentNullException("asyncResult");
4468  }
4469  OverlappedAsyncResult overlappedAsyncResult = asyncResult as OverlappedAsyncResult;
4470  if (overlappedAsyncResult == null || overlappedAsyncResult.AsyncObject != this)
4471  {
4472  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
4473  }
4474  if (overlappedAsyncResult.EndCalled)
4475  {
4476  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndReceive"));
4477  }
4478  int num = (int)overlappedAsyncResult.InternalWaitForCompletion();
4479  overlappedAsyncResult.EndCalled = true;
4480  overlappedAsyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4481  if (s_PerfCountersEnabled && num > 0)
4482  {
4483  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, num);
4484  if (Transport == TransportType.Udp)
4485  {
4486  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
4487  }
4488  }
4489  errorCode = (SocketError)overlappedAsyncResult.ErrorCode;
4490  if (errorCode != 0)
4491  {
4492  UpdateStatusAfterSocketError(errorCode);
4493  if (s_LoggingEnabled)
4494  {
4495  Logging.Exception(Logging.Sockets, this, "EndReceive", new SocketException(errorCode));
4496  Logging.Exit(Logging.Sockets, this, "EndReceive", 0);
4497  }
4498  return 0;
4499  }
4500  if (s_LoggingEnabled)
4501  {
4502  Logging.Exit(Logging.Sockets, this, "EndReceive", num);
4503  }
4504  return num;
4505  }
4506 
4527  public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
4528  {
4529  if (s_LoggingEnabled)
4530  {
4531  Logging.Enter(Logging.Sockets, this, "BeginReceiveMessageFrom", "");
4532  }
4533  if (CleanedUp)
4534  {
4535  throw new ObjectDisposedException(GetType().FullName);
4536  }
4537  if (buffer == null)
4538  {
4539  throw new ArgumentNullException("buffer");
4540  }
4541  if (remoteEP == null)
4542  {
4543  throw new ArgumentNullException("remoteEP");
4544  }
4545  if (!CanTryAddressFamily(remoteEP.AddressFamily))
4546  {
4547  throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", remoteEP.AddressFamily, addressFamily), "remoteEP");
4548  }
4549  if (offset < 0 || offset > buffer.Length)
4550  {
4551  throw new ArgumentOutOfRangeException("offset");
4552  }
4553  if (size < 0 || size > buffer.Length - offset)
4554  {
4555  throw new ArgumentOutOfRangeException("size");
4556  }
4557  if (m_RightEndPoint == null)
4558  {
4559  throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
4560  }
4561  ReceiveMessageOverlappedAsyncResult receiveMessageOverlappedAsyncResult = new ReceiveMessageOverlappedAsyncResult(this, state, callback);
4562  receiveMessageOverlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
4563  EndPoint rightEndPoint = m_RightEndPoint;
4564  SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP);
4565  SocketError socketError = SocketError.SocketError;
4566  try
4567  {
4568  receiveMessageOverlappedAsyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags, ref Caches.ReceiveOverlappedCache);
4569  receiveMessageOverlappedAsyncResult.SocketAddressOriginal = remoteEP.Serialize();
4570  SetReceivingPacketInformation();
4571  if (m_RightEndPoint == null)
4572  {
4573  m_RightEndPoint = remoteEP;
4574  }
4575  socketError = WSARecvMsg(m_Handle, Marshal.UnsafeAddrOfPinnedArrayElement((Array)receiveMessageOverlappedAsyncResult.m_MessageBuffer, 0), out int _, receiveMessageOverlappedAsyncResult.OverlappedHandle, IntPtr.Zero);
4576  if (socketError != 0)
4577  {
4578  socketError = (SocketError)Marshal.GetLastWin32Error();
4579  if (socketError == SocketError.MessageSize)
4580  {
4581  socketError = SocketError.IOPending;
4582  }
4583  }
4584  }
4585  catch (ObjectDisposedException)
4586  {
4587  m_RightEndPoint = rightEndPoint;
4588  throw;
4589  }
4590  finally
4591  {
4592  socketError = receiveMessageOverlappedAsyncResult.CheckAsyncCallOverlappedResult(socketError);
4593  }
4594  if (socketError != 0)
4595  {
4596  m_RightEndPoint = rightEndPoint;
4597  receiveMessageOverlappedAsyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4598  SocketException ex2 = new SocketException(socketError);
4599  UpdateStatusAfterSocketError(ex2);
4600  if (s_LoggingEnabled)
4601  {
4602  Logging.Exception(Logging.Sockets, this, "BeginReceiveMessageFrom", ex2);
4603  }
4604  throw ex2;
4605  }
4606  receiveMessageOverlappedAsyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
4607  if (receiveMessageOverlappedAsyncResult.CompletedSynchronously && !receiveMessageOverlappedAsyncResult.SocketAddressOriginal.Equals(receiveMessageOverlappedAsyncResult.SocketAddress))
4608  {
4609  try
4610  {
4611  remoteEP = remoteEP.Create(receiveMessageOverlappedAsyncResult.SocketAddress);
4612  }
4613  catch
4614  {
4615  }
4616  }
4617  if (s_LoggingEnabled)
4618  {
4619  Logging.Exit(Logging.Sockets, this, "BeginReceiveMessageFrom", receiveMessageOverlappedAsyncResult);
4620  }
4621  return receiveMessageOverlappedAsyncResult;
4622  }
4623 
4639  public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
4640  {
4641  if (s_LoggingEnabled)
4642  {
4643  Logging.Enter(Logging.Sockets, this, "EndReceiveMessageFrom", asyncResult);
4644  }
4645  if (CleanedUp)
4646  {
4647  throw new ObjectDisposedException(GetType().FullName);
4648  }
4649  if (endPoint == null)
4650  {
4651  throw new ArgumentNullException("endPoint");
4652  }
4653  if (!CanTryAddressFamily(endPoint.AddressFamily))
4654  {
4655  throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", endPoint.AddressFamily, addressFamily), "endPoint");
4656  }
4657  if (asyncResult == null)
4658  {
4659  throw new ArgumentNullException("asyncResult");
4660  }
4661  ReceiveMessageOverlappedAsyncResult receiveMessageOverlappedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult;
4662  if (receiveMessageOverlappedAsyncResult == null || receiveMessageOverlappedAsyncResult.AsyncObject != this)
4663  {
4664  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
4665  }
4666  if (receiveMessageOverlappedAsyncResult.EndCalled)
4667  {
4668  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndReceiveMessageFrom"));
4669  }
4670  SocketAddress socketAddress = SnapshotAndSerialize(ref endPoint);
4671  int num = (int)receiveMessageOverlappedAsyncResult.InternalWaitForCompletion();
4672  receiveMessageOverlappedAsyncResult.EndCalled = true;
4673  receiveMessageOverlappedAsyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4674  receiveMessageOverlappedAsyncResult.SocketAddress.SetSize(receiveMessageOverlappedAsyncResult.GetSocketAddressSizePtr());
4675  if (!socketAddress.Equals(receiveMessageOverlappedAsyncResult.SocketAddress))
4676  {
4677  try
4678  {
4679  endPoint = endPoint.Create(receiveMessageOverlappedAsyncResult.SocketAddress);
4680  }
4681  catch
4682  {
4683  }
4684  }
4685  if (s_PerfCountersEnabled && num > 0)
4686  {
4687  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, num);
4688  if (Transport == TransportType.Udp)
4689  {
4690  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
4691  }
4692  }
4693  if (receiveMessageOverlappedAsyncResult.ErrorCode != 0 && receiveMessageOverlappedAsyncResult.ErrorCode != 10040)
4694  {
4695  SocketException ex = new SocketException(receiveMessageOverlappedAsyncResult.ErrorCode);
4696  UpdateStatusAfterSocketError(ex);
4697  if (s_LoggingEnabled)
4698  {
4699  Logging.Exception(Logging.Sockets, this, "EndReceiveMessageFrom", ex);
4700  }
4701  throw ex;
4702  }
4703  socketFlags = receiveMessageOverlappedAsyncResult.m_flags;
4704  ipPacketInformation = receiveMessageOverlappedAsyncResult.m_IPPacketInformation;
4705  if (s_LoggingEnabled)
4706  {
4707  Logging.Exit(Logging.Sockets, this, "EndReceiveMessageFrom", num);
4708  }
4709  return num;
4710  }
4711 
4732  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
4733  public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
4734  {
4735  if (s_LoggingEnabled)
4736  {
4737  Logging.Enter(Logging.Sockets, this, "BeginReceiveFrom", "");
4738  }
4739  if (CleanedUp)
4740  {
4741  throw new ObjectDisposedException(GetType().FullName);
4742  }
4743  if (buffer == null)
4744  {
4745  throw new ArgumentNullException("buffer");
4746  }
4747  if (remoteEP == null)
4748  {
4749  throw new ArgumentNullException("remoteEP");
4750  }
4751  if (!CanTryAddressFamily(remoteEP.AddressFamily))
4752  {
4753  throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", remoteEP.AddressFamily, addressFamily), "remoteEP");
4754  }
4755  if (offset < 0 || offset > buffer.Length)
4756  {
4757  throw new ArgumentOutOfRangeException("offset");
4758  }
4759  if (size < 0 || size > buffer.Length - offset)
4760  {
4761  throw new ArgumentOutOfRangeException("size");
4762  }
4763  if (m_RightEndPoint == null)
4764  {
4765  throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
4766  }
4767  SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP);
4768  OverlappedAsyncResult overlappedAsyncResult = new OverlappedAsyncResult(this, state, callback);
4769  overlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
4770  DoBeginReceiveFrom(buffer, offset, size, socketFlags, remoteEP, socketAddress, overlappedAsyncResult);
4771  overlappedAsyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
4772  if (overlappedAsyncResult.CompletedSynchronously && !overlappedAsyncResult.SocketAddressOriginal.Equals(overlappedAsyncResult.SocketAddress))
4773  {
4774  try
4775  {
4776  remoteEP = remoteEP.Create(overlappedAsyncResult.SocketAddress);
4777  }
4778  catch
4779  {
4780  }
4781  }
4782  if (s_LoggingEnabled)
4783  {
4784  Logging.Exit(Logging.Sockets, this, "BeginReceiveFrom", overlappedAsyncResult);
4785  }
4786  return overlappedAsyncResult;
4787  }
4788 
4789  private void DoBeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint endPointSnapshot, SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
4790  {
4791  EndPoint rightEndPoint = m_RightEndPoint;
4792  SocketError socketError = SocketError.SocketError;
4793  try
4794  {
4795  asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, pinSocketAddress: true, ref Caches.ReceiveOverlappedCache);
4796  asyncResult.SocketAddressOriginal = endPointSnapshot.Serialize();
4797  if (m_RightEndPoint == null)
4798  {
4799  m_RightEndPoint = endPointSnapshot;
4800  }
4801  socketError = UnsafeNclNativeMethods.OSSOCK.WSARecvFrom(m_Handle, ref asyncResult.m_SingleBuffer, 1, out int _, ref socketFlags, asyncResult.GetSocketAddressPtr(), asyncResult.GetSocketAddressSizePtr(), asyncResult.OverlappedHandle, IntPtr.Zero);
4802  if (socketError != 0)
4803  {
4804  socketError = (SocketError)Marshal.GetLastWin32Error();
4805  }
4806  }
4807  catch (ObjectDisposedException)
4808  {
4809  m_RightEndPoint = rightEndPoint;
4810  throw;
4811  }
4812  finally
4813  {
4814  socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
4815  }
4816  if (socketError != 0)
4817  {
4818  m_RightEndPoint = rightEndPoint;
4819  asyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4820  SocketException ex2 = new SocketException(socketError);
4821  UpdateStatusAfterSocketError(ex2);
4822  if (s_LoggingEnabled)
4823  {
4824  Logging.Exception(Logging.Sockets, this, "BeginReceiveFrom", ex2);
4825  }
4826  throw ex2;
4827  }
4828  }
4829 
4842  public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint)
4843  {
4844  if (s_LoggingEnabled)
4845  {
4846  Logging.Enter(Logging.Sockets, this, "EndReceiveFrom", asyncResult);
4847  }
4848  if (CleanedUp)
4849  {
4850  throw new ObjectDisposedException(GetType().FullName);
4851  }
4852  if (endPoint == null)
4853  {
4854  throw new ArgumentNullException("endPoint");
4855  }
4856  if (!CanTryAddressFamily(endPoint.AddressFamily))
4857  {
4858  throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", endPoint.AddressFamily, addressFamily), "endPoint");
4859  }
4860  if (asyncResult == null)
4861  {
4862  throw new ArgumentNullException("asyncResult");
4863  }
4864  OverlappedAsyncResult overlappedAsyncResult = asyncResult as OverlappedAsyncResult;
4865  if (overlappedAsyncResult == null || overlappedAsyncResult.AsyncObject != this)
4866  {
4867  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
4868  }
4869  if (overlappedAsyncResult.EndCalled)
4870  {
4871  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndReceiveFrom"));
4872  }
4873  SocketAddress socketAddress = SnapshotAndSerialize(ref endPoint);
4874  int num = (int)overlappedAsyncResult.InternalWaitForCompletion();
4875  overlappedAsyncResult.EndCalled = true;
4876  overlappedAsyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4877  overlappedAsyncResult.SocketAddress.SetSize(overlappedAsyncResult.GetSocketAddressSizePtr());
4878  if (!socketAddress.Equals(overlappedAsyncResult.SocketAddress))
4879  {
4880  try
4881  {
4882  endPoint = endPoint.Create(overlappedAsyncResult.SocketAddress);
4883  }
4884  catch
4885  {
4886  }
4887  }
4888  if (s_PerfCountersEnabled && num > 0)
4889  {
4890  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, num);
4891  if (Transport == TransportType.Udp)
4892  {
4893  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
4894  }
4895  }
4896  if (overlappedAsyncResult.ErrorCode != 0)
4897  {
4898  SocketException ex = new SocketException(overlappedAsyncResult.ErrorCode);
4899  UpdateStatusAfterSocketError(ex);
4900  if (s_LoggingEnabled)
4901  {
4902  Logging.Exception(Logging.Sockets, this, "EndReceiveFrom", ex);
4903  }
4904  throw ex;
4905  }
4906  if (s_LoggingEnabled)
4907  {
4908  Logging.Exit(Logging.Sockets, this, "EndReceiveFrom", num);
4909  }
4910  return num;
4911  }
4912 
4923  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
4924  public IAsyncResult BeginAccept(AsyncCallback callback, object state)
4925  {
4926  if (CanUseAcceptEx)
4927  {
4928  return BeginAccept(0, callback, state);
4929  }
4930  if (s_LoggingEnabled)
4931  {
4932  Logging.Enter(Logging.Sockets, this, "BeginAccept", "");
4933  }
4934  if (CleanedUp)
4935  {
4936  throw new ObjectDisposedException(GetType().FullName);
4937  }
4938  AcceptAsyncResult acceptAsyncResult = new AcceptAsyncResult(this, state, callback);
4939  acceptAsyncResult.StartPostingAsyncOp(lockCapture: false);
4940  DoBeginAccept(acceptAsyncResult);
4941  acceptAsyncResult.FinishPostingAsyncOp(ref Caches.AcceptClosureCache);
4942  if (s_LoggingEnabled)
4943  {
4944  Logging.Exit(Logging.Sockets, this, "BeginAccept", acceptAsyncResult);
4945  }
4946  return acceptAsyncResult;
4947  }
4948 
4949  private void DoBeginAccept(LazyAsyncResult asyncResult)
4950  {
4951  if (m_RightEndPoint == null)
4952  {
4953  throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
4954  }
4955  if (!isListening)
4956  {
4957  throw new InvalidOperationException(SR.GetString("net_sockets_mustlisten"));
4958  }
4959  bool flag = false;
4960  SocketError socketError = SocketError.Success;
4961  Queue acceptQueue = GetAcceptQueue();
4962  lock (this)
4963  {
4964  if (acceptQueue.Count == 0)
4965  {
4966  SocketAddress socketAddress = m_RightEndPoint.Serialize();
4967  InternalSetBlocking(desired: false);
4968  SafeCloseSocket safeCloseSocket = null;
4969  try
4970  {
4971  safeCloseSocket = SafeCloseSocket.Accept(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size);
4972  socketError = (SocketError)(safeCloseSocket.IsInvalid ? Marshal.GetLastWin32Error() : 0);
4973  }
4974  catch (ObjectDisposedException)
4975  {
4976  socketError = SocketError.NotSocket;
4977  }
4978  if (socketError != SocketError.WouldBlock)
4979  {
4980  if (socketError == SocketError.Success)
4981  {
4982  asyncResult.Result = CreateAcceptSocket(safeCloseSocket, m_RightEndPoint.Create(socketAddress), needCancelSelect: false);
4983  }
4984  else
4985  {
4986  asyncResult.ErrorCode = (int)socketError;
4987  }
4988  InternalSetBlocking(desired: true);
4989  flag = true;
4990  }
4991  else
4992  {
4993  acceptQueue.Enqueue(asyncResult);
4994  if (!SetAsyncEventSelect(AsyncEventBits.FdAccept))
4995  {
4996  acceptQueue.Dequeue();
4997  throw new ObjectDisposedException(GetType().FullName);
4998  }
4999  }
5000  }
5001  else
5002  {
5003  acceptQueue.Enqueue(asyncResult);
5004  }
5005  }
5006  if (!flag)
5007  {
5008  return;
5009  }
5010  if (socketError == SocketError.Success)
5011  {
5012  asyncResult.InvokeCallback();
5013  return;
5014  }
5015  SocketException ex2 = new SocketException(socketError);
5016  UpdateStatusAfterSocketError(ex2);
5017  if (s_LoggingEnabled)
5018  {
5019  Logging.Exception(Logging.Sockets, this, "BeginAccept", ex2);
5020  }
5021  throw ex2;
5022  }
5023 
5024  private void CompleteAcceptResults(object nullState)
5025  {
5026  Queue acceptQueue = GetAcceptQueue();
5027  bool flag = true;
5028  while (flag)
5029  {
5030  LazyAsyncResult lazyAsyncResult = null;
5031  lock (this)
5032  {
5033  if (acceptQueue.Count == 0)
5034  {
5035  return;
5036  }
5037  lazyAsyncResult = (LazyAsyncResult)acceptQueue.Dequeue();
5038  if (acceptQueue.Count == 0)
5039  {
5040  flag = false;
5041  }
5042  }
5043  try
5044  {
5045  lazyAsyncResult.InvokeCallback(new SocketException(SocketError.OperationAborted));
5046  }
5047  catch
5048  {
5049  if (flag)
5050  {
5051  ThreadPool.UnsafeQueueUserWorkItem(CompleteAcceptResults, null);
5052  }
5053  throw;
5054  }
5055  }
5056  }
5057 
5058  private void AcceptCallback(object nullState)
5059  {
5060  bool flag = true;
5061  Queue acceptQueue = GetAcceptQueue();
5062  while (flag)
5063  {
5064  LazyAsyncResult lazyAsyncResult = null;
5065  SocketError socketError = SocketError.OperationAborted;
5066  SocketAddress socketAddress = null;
5067  SafeCloseSocket safeCloseSocket = null;
5068  Exception ex = null;
5069  object result = null;
5070  lock (this)
5071  {
5072  if (acceptQueue.Count == 0)
5073  {
5074  return;
5075  }
5076  lazyAsyncResult = (LazyAsyncResult)acceptQueue.Peek();
5077  if (!CleanedUp)
5078  {
5079  socketAddress = m_RightEndPoint.Serialize();
5080  try
5081  {
5082  safeCloseSocket = SafeCloseSocket.Accept(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size);
5083  socketError = (SocketError)(safeCloseSocket.IsInvalid ? Marshal.GetLastWin32Error() : 0);
5084  }
5085  catch (ObjectDisposedException)
5086  {
5087  socketError = SocketError.OperationAborted;
5088  }
5089  catch (Exception ex3)
5090  {
5091  if (NclUtilities.IsFatal(ex3))
5092  {
5093  throw;
5094  }
5095  ex = ex3;
5096  }
5097  }
5098  if (socketError == SocketError.WouldBlock && ex == null)
5099  {
5100  try
5101  {
5102  m_AsyncEvent.Reset();
5103  if (SetAsyncEventSelect(AsyncEventBits.FdAccept))
5104  {
5105  return;
5106  }
5107  }
5108  catch (ObjectDisposedException)
5109  {
5110  }
5111  ex = new ObjectDisposedException(GetType().FullName);
5112  }
5113  if (ex != null)
5114  {
5115  result = ex;
5116  }
5117  else if (socketError == SocketError.Success)
5118  {
5119  result = CreateAcceptSocket(safeCloseSocket, m_RightEndPoint.Create(socketAddress), needCancelSelect: true);
5120  }
5121  else
5122  {
5123  lazyAsyncResult.ErrorCode = (int)socketError;
5124  }
5125  acceptQueue.Dequeue();
5126  if (acceptQueue.Count == 0)
5127  {
5128  if (!CleanedUp)
5129  {
5130  UnsetAsyncEventSelect();
5131  }
5132  flag = false;
5133  }
5134  }
5135  try
5136  {
5137  lazyAsyncResult.InvokeCallback(result);
5138  }
5139  catch
5140  {
5141  if (flag)
5142  {
5143  ThreadPool.UnsafeQueueUserWorkItem(AcceptCallback, nullState);
5144  }
5145  throw;
5146  }
5147  }
5148  }
5149 
5161  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
5162  public IAsyncResult BeginAccept(int receiveSize, AsyncCallback callback, object state)
5163  {
5164  return BeginAccept(null, receiveSize, callback, state);
5165  }
5166 
5179  [HostProtection(SecurityAction.LinkDemand, ExternalThreading = true)]
5180  public IAsyncResult BeginAccept(Socket acceptSocket, int receiveSize, AsyncCallback callback, object state)
5181  {
5182  if (s_LoggingEnabled)
5183  {
5184  Logging.Enter(Logging.Sockets, this, "BeginAccept", "");
5185  }
5186  if (CleanedUp)
5187  {
5188  throw new ObjectDisposedException(GetType().FullName);
5189  }
5190  if (receiveSize < 0)
5191  {
5192  throw new ArgumentOutOfRangeException("size");
5193  }
5194  AcceptOverlappedAsyncResult acceptOverlappedAsyncResult = new AcceptOverlappedAsyncResult(this, state, callback);
5195  acceptOverlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
5196  DoBeginAccept(acceptSocket, receiveSize, acceptOverlappedAsyncResult);
5197  acceptOverlappedAsyncResult.FinishPostingAsyncOp(ref Caches.AcceptClosureCache);
5198  if (s_LoggingEnabled)
5199  {
5200  Logging.Exit(Logging.Sockets, this, "BeginAccept", acceptOverlappedAsyncResult);
5201  }
5202  return acceptOverlappedAsyncResult;
5203  }
5204 
5205  private void DoBeginAccept(Socket acceptSocket, int receiveSize, AcceptOverlappedAsyncResult asyncResult)
5206  {
5207  if (m_RightEndPoint == null)
5208  {
5209  throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
5210  }
5211  if (!isListening)
5212  {
5213  throw new InvalidOperationException(SR.GetString("net_sockets_mustlisten"));
5214  }
5215  if (acceptSocket == null)
5216  {
5217  acceptSocket = new Socket(addressFamily, socketType, protocolType);
5218  }
5219  else if (acceptSocket.m_RightEndPoint != null)
5220  {
5221  throw new InvalidOperationException(SR.GetString("net_sockets_namedmustnotbebound", "acceptSocket"));
5222  }
5223  asyncResult.AcceptSocket = acceptSocket;
5224  int num = m_RightEndPoint.Serialize().Size + 16;
5225  byte[] buffer = new byte[receiveSize + num * 2];
5226  asyncResult.SetUnmanagedStructures(buffer, num);
5227  SocketError errorCode = SocketError.Success;
5228  if (!AcceptEx(m_Handle, acceptSocket.m_Handle, Marshal.UnsafeAddrOfPinnedArrayElement((Array)asyncResult.Buffer, 0), receiveSize, num, num, out int _, asyncResult.OverlappedHandle))
5229  {
5230  errorCode = (SocketError)Marshal.GetLastWin32Error();
5231  }
5232  errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode);
5233  if (errorCode != 0)
5234  {
5235  SocketException ex = new SocketException(errorCode);
5236  UpdateStatusAfterSocketError(ex);
5237  if (s_LoggingEnabled)
5238  {
5239  Logging.Exception(Logging.Sockets, this, "BeginAccept", ex);
5240  }
5241  throw ex;
5242  }
5243  }
5244 
5257  public Socket EndAccept(IAsyncResult asyncResult)
5258  {
5259  if (s_LoggingEnabled)
5260  {
5261  Logging.Enter(Logging.Sockets, this, "EndAccept", asyncResult);
5262  }
5263  if (CleanedUp)
5264  {
5265  throw new ObjectDisposedException(GetType().FullName);
5266  }
5267  byte[] buffer;
5268  int bytesTransferred;
5269  if (asyncResult != null && asyncResult is AcceptOverlappedAsyncResult)
5270  {
5271  return EndAccept(out buffer, out bytesTransferred, asyncResult);
5272  }
5273  if (asyncResult == null)
5274  {
5275  throw new ArgumentNullException("asyncResult");
5276  }
5277  AcceptAsyncResult acceptAsyncResult = asyncResult as AcceptAsyncResult;
5278  if (acceptAsyncResult == null || acceptAsyncResult.AsyncObject != this)
5279  {
5280  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
5281  }
5282  if (acceptAsyncResult.EndCalled)
5283  {
5284  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndAccept"));
5285  }
5286  object obj = acceptAsyncResult.InternalWaitForCompletion();
5287  acceptAsyncResult.EndCalled = true;
5288  Exception ex = obj as Exception;
5289  if (ex != null)
5290  {
5291  throw ex;
5292  }
5293  if (acceptAsyncResult.ErrorCode != 0)
5294  {
5295  SocketException ex2 = new SocketException(acceptAsyncResult.ErrorCode);
5296  UpdateStatusAfterSocketError(ex2);
5297  if (s_LoggingEnabled)
5298  {
5299  Logging.Exception(Logging.Sockets, this, "EndAccept", ex2);
5300  }
5301  throw ex2;
5302  }
5303  Socket socket = (Socket)obj;
5304  if (s_LoggingEnabled)
5305  {
5306  Logging.PrintInfo(Logging.Sockets, socket, SR.GetString("net_log_socket_accepted", socket.RemoteEndPoint, socket.LocalEndPoint));
5307  Logging.Exit(Logging.Sockets, this, "EndAccept", obj);
5308  }
5309  return socket;
5310  }
5311 
5325  public Socket EndAccept(out byte[] buffer, IAsyncResult asyncResult)
5326  {
5327  byte[] buffer2;
5328  int bytesTransferred;
5329  Socket result = EndAccept(out buffer2, out bytesTransferred, asyncResult);
5330  buffer = new byte[bytesTransferred];
5331  Array.Copy(buffer2, buffer, bytesTransferred);
5332  return result;
5333  }
5334 
5349  public Socket EndAccept(out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
5350  {
5351  if (s_LoggingEnabled)
5352  {
5353  Logging.Enter(Logging.Sockets, this, "EndAccept", asyncResult);
5354  }
5355  if (CleanedUp)
5356  {
5357  throw new ObjectDisposedException(GetType().FullName);
5358  }
5359  if (asyncResult == null)
5360  {
5361  throw new ArgumentNullException("asyncResult");
5362  }
5363  AcceptOverlappedAsyncResult acceptOverlappedAsyncResult = asyncResult as AcceptOverlappedAsyncResult;
5364  if (acceptOverlappedAsyncResult == null || acceptOverlappedAsyncResult.AsyncObject != this)
5365  {
5366  throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
5367  }
5368  if (acceptOverlappedAsyncResult.EndCalled)
5369  {
5370  throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", "EndAccept"));
5371  }
5372  Socket socket = (Socket)acceptOverlappedAsyncResult.InternalWaitForCompletion();
5373  bytesTransferred = acceptOverlappedAsyncResult.BytesTransferred;
5374  buffer = acceptOverlappedAsyncResult.Buffer;
5375  acceptOverlappedAsyncResult.EndCalled = true;
5376  if (s_PerfCountersEnabled && bytesTransferred > 0)
5377  {
5378  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, bytesTransferred);
5379  }
5380  if (acceptOverlappedAsyncResult.ErrorCode != 0)
5381  {
5382  SocketException ex = new SocketException(acceptOverlappedAsyncResult.ErrorCode);
5383  UpdateStatusAfterSocketError(ex);
5384  if (s_LoggingEnabled)
5385  {
5386  Logging.Exception(Logging.Sockets, this, "EndAccept", ex);
5387  }
5388  throw ex;
5389  }
5390  if (s_LoggingEnabled)
5391  {
5392  Logging.PrintInfo(Logging.Sockets, socket, SR.GetString("net_log_socket_accepted", socket.RemoteEndPoint, socket.LocalEndPoint));
5393  Logging.Exit(Logging.Sockets, this, "EndAccept", socket);
5394  }
5395  return socket;
5396  }
5397 
5402  public void Shutdown(SocketShutdown how)
5403  {
5404  if (s_LoggingEnabled)
5405  {
5406  Logging.Enter(Logging.Sockets, this, "Shutdown", how);
5407  }
5408  if (CleanedUp)
5409  {
5410  throw new ObjectDisposedException(GetType().FullName);
5411  }
5412  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.shutdown(m_Handle, (int)how);
5413  socketError = (SocketError)((socketError == SocketError.SocketError) ? Marshal.GetLastWin32Error() : 0);
5414  if (socketError != 0 && socketError != SocketError.NotSocket)
5415  {
5416  SocketException ex = new SocketException(socketError);
5417  UpdateStatusAfterSocketError(ex);
5418  if (s_LoggingEnabled)
5419  {
5420  Logging.Exception(Logging.Sockets, this, "Shutdown", ex);
5421  }
5422  throw ex;
5423  }
5424  SetToDisconnected();
5425  InternalSetBlocking(willBlockInternal);
5426  if (s_LoggingEnabled)
5427  {
5428  Logging.Exit(Logging.Sockets, this, "Shutdown", "");
5429  }
5430  }
5431 
5432  private void EnsureDynamicWinsockMethods()
5433  {
5434  if (m_DynamicWinsockMethods == null)
5435  {
5436  m_DynamicWinsockMethods = DynamicWinsockMethods.GetMethods(addressFamily, socketType, protocolType);
5437  }
5438  }
5439 
5440  private bool AcceptEx(SafeCloseSocket listenSocketHandle, SafeCloseSocket acceptSocketHandle, IntPtr buffer, int len, int localAddressLength, int remoteAddressLength, out int bytesReceived, SafeHandle overlapped)
5441  {
5442  EnsureDynamicWinsockMethods();
5443  AcceptExDelegate @delegate = m_DynamicWinsockMethods.GetDelegate<AcceptExDelegate>(listenSocketHandle);
5444  return @delegate(listenSocketHandle, acceptSocketHandle, buffer, len, localAddressLength, remoteAddressLength, out bytesReceived, overlapped);
5445  }
5446 
5447  internal void GetAcceptExSockaddrs(IntPtr buffer, int receiveDataLength, int localAddressLength, int remoteAddressLength, out IntPtr localSocketAddress, out int localSocketAddressLength, out IntPtr remoteSocketAddress, out int remoteSocketAddressLength)
5448  {
5449  EnsureDynamicWinsockMethods();
5450  GetAcceptExSockaddrsDelegate @delegate = m_DynamicWinsockMethods.GetDelegate<GetAcceptExSockaddrsDelegate>(m_Handle);
5451  @delegate(buffer, receiveDataLength, localAddressLength, remoteAddressLength, out localSocketAddress, out localSocketAddressLength, out remoteSocketAddress, out remoteSocketAddressLength);
5452  }
5453 
5454  private bool DisconnectEx(SafeCloseSocket socketHandle, SafeHandle overlapped, int flags, int reserved)
5455  {
5456  EnsureDynamicWinsockMethods();
5457  DisconnectExDelegate @delegate = m_DynamicWinsockMethods.GetDelegate<DisconnectExDelegate>(socketHandle);
5458  return @delegate(socketHandle, overlapped, flags, reserved);
5459  }
5460 
5461  private bool DisconnectEx_Blocking(IntPtr socketHandle, IntPtr overlapped, int flags, int reserved)
5462  {
5463  EnsureDynamicWinsockMethods();
5464  DisconnectExDelegate_Blocking @delegate = m_DynamicWinsockMethods.GetDelegate<DisconnectExDelegate_Blocking>(m_Handle);
5465  return @delegate(socketHandle, overlapped, flags, reserved);
5466  }
5467 
5468  private bool ConnectEx(SafeCloseSocket socketHandle, IntPtr socketAddress, int socketAddressSize, IntPtr buffer, int dataLength, out int bytesSent, SafeHandle overlapped)
5469  {
5470  EnsureDynamicWinsockMethods();
5471  ConnectExDelegate @delegate = m_DynamicWinsockMethods.GetDelegate<ConnectExDelegate>(socketHandle);
5472  return @delegate(socketHandle, socketAddress, socketAddressSize, buffer, dataLength, out bytesSent, overlapped);
5473  }
5474 
5475  private SocketError WSARecvMsg(SafeCloseSocket socketHandle, IntPtr msg, out int bytesTransferred, SafeHandle overlapped, IntPtr completionRoutine)
5476  {
5477  EnsureDynamicWinsockMethods();
5478  WSARecvMsgDelegate @delegate = m_DynamicWinsockMethods.GetDelegate<WSARecvMsgDelegate>(socketHandle);
5479  return @delegate(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
5480  }
5481 
5482  private SocketError WSARecvMsg_Blocking(IntPtr socketHandle, IntPtr msg, out int bytesTransferred, IntPtr overlapped, IntPtr completionRoutine)
5483  {
5484  EnsureDynamicWinsockMethods();
5485  WSARecvMsgDelegate_Blocking @delegate = m_DynamicWinsockMethods.GetDelegate<WSARecvMsgDelegate_Blocking>(m_Handle);
5486  return @delegate(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
5487  }
5488 
5489  private bool TransmitPackets(SafeCloseSocket socketHandle, IntPtr packetArray, int elementCount, int sendSize, SafeNativeOverlapped overlapped, TransmitFileOptions flags)
5490  {
5491  EnsureDynamicWinsockMethods();
5492  TransmitPacketsDelegate @delegate = m_DynamicWinsockMethods.GetDelegate<TransmitPacketsDelegate>(socketHandle);
5493  return @delegate(socketHandle, packetArray, elementCount, sendSize, overlapped, flags);
5494  }
5495 
5496  private Queue GetAcceptQueue()
5497  {
5498  if (m_AcceptQueueOrConnectResult == null)
5499  {
5500  Interlocked.CompareExchange(ref m_AcceptQueueOrConnectResult, new Queue(16), null);
5501  }
5502  return (Queue)m_AcceptQueueOrConnectResult;
5503  }
5504 
5505  private void CheckSetOptionPermissions(SocketOptionLevel optionLevel, SocketOptionName optionName)
5506  {
5507  if ((optionLevel != SocketOptionLevel.Tcp || (optionName != SocketOptionName.Debug && optionName != SocketOptionName.AcceptConnection && optionName != SocketOptionName.AcceptConnection)) && (optionLevel != SocketOptionLevel.Udp || (optionName != SocketOptionName.Debug && optionName != SocketOptionName.ChecksumCoverage)) && (optionLevel != SocketOptionLevel.Socket || (optionName != SocketOptionName.KeepAlive && optionName != SocketOptionName.Linger && optionName != SocketOptionName.DontLinger && optionName != SocketOptionName.SendBuffer && optionName != SocketOptionName.ReceiveBuffer && optionName != SocketOptionName.SendTimeout && optionName != SocketOptionName.ExclusiveAddressUse && optionName != SocketOptionName.ReceiveTimeout)) && (optionLevel != SocketOptionLevel.IPv6 || optionName != SocketOptionName.IPProtectionLevel))
5508  {
5509  ExceptionHelper.UnmanagedPermission.Demand();
5510  }
5511  }
5512 
5513  private SocketAddress SnapshotAndSerialize(ref EndPoint remoteEP)
5514  {
5515  IPEndPoint iPEndPoint = remoteEP as IPEndPoint;
5516  if (iPEndPoint != null)
5517  {
5518  iPEndPoint = iPEndPoint.Snapshot();
5519  remoteEP = RemapIPEndPoint(iPEndPoint);
5520  }
5521  return CallSerializeCheckDnsEndPoint(remoteEP);
5522  }
5523 
5524  private SocketAddress CallSerializeCheckDnsEndPoint(EndPoint remoteEP)
5525  {
5526  if (remoteEP is DnsEndPoint)
5527  {
5528  throw new ArgumentException(SR.GetString("net_sockets_invalid_dnsendpoint", "remoteEP"), "remoteEP");
5529  }
5530  return remoteEP.Serialize();
5531  }
5532 
5533  private IPEndPoint RemapIPEndPoint(IPEndPoint input)
5534  {
5535  if (input.AddressFamily == AddressFamily.InterNetwork && IsDualMode)
5536  {
5537  return new IPEndPoint(input.Address.MapToIPv6(), input.Port);
5538  }
5539  return input;
5540  }
5541 
5542  private SocketAddress CheckCacheRemote(ref EndPoint remoteEP, bool isOverwrite)
5543  {
5544  IPEndPoint iPEndPoint = remoteEP as IPEndPoint;
5545  if (iPEndPoint != null)
5546  {
5547  iPEndPoint = iPEndPoint.Snapshot();
5548  remoteEP = RemapIPEndPoint(iPEndPoint);
5549  }
5550  SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(remoteEP);
5551  SocketAddress permittedRemoteAddress = m_PermittedRemoteAddress;
5552  if (permittedRemoteAddress != null && permittedRemoteAddress.Equals(socketAddress))
5553  {
5554  return permittedRemoteAddress;
5555  }
5556  if (iPEndPoint != null)
5557  {
5558  SocketPermission socketPermission = new SocketPermission(NetworkAccess.Connect, Transport, iPEndPoint.Address.ToString(), iPEndPoint.Port);
5559  socketPermission.Demand();
5560  }
5561  else
5562  {
5563  ExceptionHelper.UnmanagedPermission.Demand();
5564  }
5565  if ((m_PermittedRemoteAddress == null) | isOverwrite)
5566  {
5567  m_PermittedRemoteAddress = socketAddress;
5568  }
5569  return socketAddress;
5570  }
5571 
5572  internal static void InitializeSockets()
5573  {
5574  if (!s_Initialized)
5575  {
5576  lock (InternalSyncObject)
5577  {
5578  if (!s_Initialized)
5579  {
5580  WSAData lpWSAData = default(WSAData);
5581  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.WSAStartup(514, out lpWSAData);
5582  if (socketError != 0)
5583  {
5584  throw new SocketException(socketError);
5585  }
5586  bool flag = true;
5587  bool flag2 = true;
5588  SafeCloseSocket.InnerSafeCloseSocket innerSafeCloseSocket = UnsafeNclNativeMethods.OSSOCK.WSASocket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP, IntPtr.Zero, 0u, (SocketConstructorFlags)0);
5589  if (innerSafeCloseSocket.IsInvalid)
5590  {
5591  socketError = (SocketError)Marshal.GetLastWin32Error();
5592  if (socketError == SocketError.AddressFamilyNotSupported)
5593  {
5594  flag = false;
5595  }
5596  }
5597  innerSafeCloseSocket.Close();
5598  SafeCloseSocket.InnerSafeCloseSocket innerSafeCloseSocket2 = UnsafeNclNativeMethods.OSSOCK.WSASocket(AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.IP, IntPtr.Zero, 0u, (SocketConstructorFlags)0);
5599  if (innerSafeCloseSocket2.IsInvalid)
5600  {
5601  socketError = (SocketError)Marshal.GetLastWin32Error();
5602  if (socketError == SocketError.AddressFamilyNotSupported)
5603  {
5604  flag2 = false;
5605  }
5606  }
5607  innerSafeCloseSocket2.Close();
5608  if (flag2)
5609  {
5610  s_OSSupportsIPv6 = true;
5611  flag2 = SettingsSectionInternal.Section.Ipv6Enabled;
5612  }
5613  s_SupportsIPv4 = flag;
5614  s_SupportsIPv6 = flag2;
5615  s_PerfCountersEnabled = NetworkingPerfCounters.Instance.Enabled;
5616  s_Initialized = true;
5617  }
5618  }
5619  }
5620  }
5621 
5622  internal void InternalConnect(EndPoint remoteEP)
5623  {
5624  EndPoint remoteEP2 = remoteEP;
5625  SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP2);
5626  DoConnect(remoteEP2, socketAddress);
5627  }
5628 
5629  private void DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
5630  {
5631  if (s_LoggingEnabled)
5632  {
5633  Logging.Enter(Logging.Sockets, this, "Connect", endPointSnapshot);
5634  }
5635  if (UnsafeNclNativeMethods.OSSOCK.WSAConnect(m_Handle.DangerousGetHandle(), socketAddress.m_Buffer, socketAddress.m_Size, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) != 0)
5636  {
5637  SocketException ex = new SocketException(endPointSnapshot);
5638  UpdateStatusAfterSocketError(ex);
5639  if (s_LoggingEnabled)
5640  {
5641  Logging.Exception(Logging.Sockets, this, "Connect", ex);
5642  }
5643  throw ex;
5644  }
5645  if (m_RightEndPoint == null)
5646  {
5647  m_RightEndPoint = endPointSnapshot;
5648  }
5649  SetToConnected();
5650  if (s_LoggingEnabled)
5651  {
5652  Logging.PrintInfo(Logging.Sockets, this, SR.GetString("net_log_socket_connected", LocalEndPoint, RemoteEndPoint));
5653  Logging.Exit(Logging.Sockets, this, "Connect", "");
5654  }
5655  }
5656 
5660  protected virtual void Dispose(bool disposing)
5661  {
5662  if (!disposing)
5663  {
5664  return;
5665  }
5666  try
5667  {
5668  if (s_LoggingEnabled)
5669  {
5670  Logging.Enter(Logging.Sockets, this, "Dispose", null);
5671  }
5672  }
5673  catch (Exception exception)
5674  {
5675  if (NclUtilities.IsFatal(exception))
5676  {
5677  throw;
5678  }
5679  }
5680  int num;
5681  while ((num = Interlocked.CompareExchange(ref m_IntCleanedUp, 1, 0)) == 2)
5682  {
5683  Thread.SpinWait(1);
5684  }
5685  if (num == 1)
5686  {
5687  try
5688  {
5689  if (s_LoggingEnabled)
5690  {
5691  Logging.Exit(Logging.Sockets, this, "Dispose", null);
5692  }
5693  }
5694  catch (Exception exception2)
5695  {
5696  if (NclUtilities.IsFatal(exception2))
5697  {
5698  throw;
5699  }
5700  }
5701  return;
5702  }
5703  SetToDisconnected();
5704  AsyncEventBits asyncEventBits = AsyncEventBits.FdNone;
5705  if (m_BlockEventBits != 0)
5706  {
5707  UnsetAsyncEventSelect();
5708  if (m_BlockEventBits == AsyncEventBits.FdConnect)
5709  {
5710  LazyAsyncResult lazyAsyncResult = m_AcceptQueueOrConnectResult as LazyAsyncResult;
5711  if (lazyAsyncResult != null && !lazyAsyncResult.InternalPeekCompleted)
5712  {
5713  asyncEventBits = AsyncEventBits.FdConnect;
5714  }
5715  }
5716  else if (m_BlockEventBits == AsyncEventBits.FdAccept)
5717  {
5718  Queue queue = m_AcceptQueueOrConnectResult as Queue;
5719  if (queue != null && queue.Count != 0)
5720  {
5721  asyncEventBits = AsyncEventBits.FdAccept;
5722  }
5723  }
5724  }
5725  try
5726  {
5727  int optionValue = m_CloseTimeout;
5728  if (optionValue == 0)
5729  {
5730  m_Handle.Dispose();
5731  }
5732  else
5733  {
5734  if (!willBlock || !willBlockInternal)
5735  {
5736  int argp = 0;
5737  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.ioctlsocket(m_Handle, -2147195266, ref argp);
5738  }
5739  if (optionValue < 0)
5740  {
5741  m_Handle.CloseAsIs();
5742  }
5743  else
5744  {
5745  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.shutdown(m_Handle, 1);
5746  if (UnsafeNclNativeMethods.OSSOCK.setsockopt(m_Handle, SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, ref optionValue, 4) != 0)
5747  {
5748  m_Handle.Dispose();
5749  }
5750  else if (UnsafeNclNativeMethods.OSSOCK.recv(m_Handle.DangerousGetHandle(), null, 0, SocketFlags.None) != 0)
5751  {
5752  m_Handle.Dispose();
5753  }
5754  else
5755  {
5756  int argp2 = 0;
5757  if (UnsafeNclNativeMethods.OSSOCK.ioctlsocket(m_Handle, 1074030207, ref argp2) != 0 || argp2 != 0)
5758  {
5759  m_Handle.Dispose();
5760  }
5761  else
5762  {
5763  m_Handle.CloseAsIs();
5764  }
5765  }
5766  }
5767  }
5768  }
5769  catch (ObjectDisposedException)
5770  {
5771  }
5772  if (m_Caches != null)
5773  {
5774  OverlappedCache.InterlockedFree(ref m_Caches.SendOverlappedCache);
5775  OverlappedCache.InterlockedFree(ref m_Caches.ReceiveOverlappedCache);
5776  }
5777  switch (asyncEventBits)
5778  {
5779  case AsyncEventBits.FdConnect:
5780  ThreadPool.UnsafeQueueUserWorkItem(((LazyAsyncResult)m_AcceptQueueOrConnectResult).InvokeCallback, new SocketException(SocketError.OperationAborted));
5781  break;
5782  case AsyncEventBits.FdAccept:
5783  ThreadPool.UnsafeQueueUserWorkItem(CompleteAcceptResults, null);
5784  break;
5785  }
5786  if (m_AsyncEvent != null)
5787  {
5788  m_AsyncEvent.Close();
5789  }
5790  }
5791 
5793  public void Dispose()
5794  {
5795  Dispose(disposing: true);
5796  GC.SuppressFinalize(this);
5797  }
5798 
5800  ~Socket()
5801  {
5802  Dispose(disposing: false);
5803  }
5804 
5805  internal void InternalShutdown(SocketShutdown how)
5806  {
5807  if (!CleanedUp && !m_Handle.IsInvalid)
5808  {
5809  try
5810  {
5811  UnsafeNclNativeMethods.OSSOCK.shutdown(m_Handle, (int)how);
5812  }
5813  catch (ObjectDisposedException)
5814  {
5815  }
5816  }
5817  }
5818 
5819  internal void SetReceivingPacketInformation()
5820  {
5821  if (!m_ReceivingPacketInformation)
5822  {
5823  IPAddress iPAddress = (m_RightEndPoint as IPEndPoint)?.Address;
5824  if (addressFamily == AddressFamily.InterNetwork || (iPAddress != null && IsDualMode && (iPAddress.IsIPv4MappedToIPv6 || iPAddress.Equals(IPAddress.IPv6Any))))
5825  {
5826  SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, optionValue: true);
5827  }
5828  if (addressFamily == AddressFamily.InterNetworkV6 && (iPAddress == null || !iPAddress.IsIPv4MappedToIPv6))
5829  {
5830  SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.PacketInformation, optionValue: true);
5831  }
5832  m_ReceivingPacketInformation = true;
5833  }
5834  }
5835 
5836  internal void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue, bool silent)
5837  {
5838  if (silent && (CleanedUp || m_Handle.IsInvalid))
5839  {
5840  return;
5841  }
5842  SocketError socketError = SocketError.Success;
5843  try
5844  {
5845  socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(m_Handle, optionLevel, optionName, ref optionValue, 4);
5846  }
5847  catch
5848  {
5849  if (silent && m_Handle.IsInvalid)
5850  {
5851  return;
5852  }
5853  throw;
5854  }
5855  if (optionName == SocketOptionName.PacketInformation && optionValue == 0 && socketError == SocketError.Success)
5856  {
5857  m_ReceivingPacketInformation = false;
5858  }
5859  if (silent || socketError != SocketError.SocketError)
5860  {
5861  return;
5862  }
5863  SocketException ex = new SocketException();
5864  UpdateStatusAfterSocketError(ex);
5865  if (s_LoggingEnabled)
5866  {
5867  Logging.Exception(Logging.Sockets, this, "SetSocketOption", ex);
5868  }
5869  throw ex;
5870  }
5871 
5872  private void setMulticastOption(SocketOptionName optionName, MulticastOption MR)
5873  {
5874  IPMulticastRequest mreq = default(IPMulticastRequest);
5875  mreq.MulticastAddress = (int)MR.Group.m_Address;
5876  if (MR.LocalAddress == null)
5877  {
5878  int num = mreq.InterfaceAddress = IPAddress.HostToNetworkOrder(MR.InterfaceIndex);
5879  }
5880  else
5881  {
5882  mreq.InterfaceAddress = (int)MR.LocalAddress.m_Address;
5883  }
5884  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(m_Handle, SocketOptionLevel.IP, optionName, ref mreq, IPMulticastRequest.Size);
5885  if (socketError == SocketError.SocketError)
5886  {
5887  SocketException ex = new SocketException();
5888  UpdateStatusAfterSocketError(ex);
5889  if (s_LoggingEnabled)
5890  {
5891  Logging.Exception(Logging.Sockets, this, "setMulticastOption", ex);
5892  }
5893  throw ex;
5894  }
5895  }
5896 
5897  private void setIPv6MulticastOption(SocketOptionName optionName, IPv6MulticastOption MR)
5898  {
5899  IPv6MulticastRequest mreq = default(IPv6MulticastRequest);
5900  mreq.MulticastAddress = MR.Group.GetAddressBytes();
5901  mreq.InterfaceIndex = (int)MR.InterfaceIndex;
5902  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(m_Handle, SocketOptionLevel.IPv6, optionName, ref mreq, IPv6MulticastRequest.Size);
5903  if (socketError == SocketError.SocketError)
5904  {
5905  SocketException ex = new SocketException();
5906  UpdateStatusAfterSocketError(ex);
5907  if (s_LoggingEnabled)
5908  {
5909  Logging.Exception(Logging.Sockets, this, "setIPv6MulticastOption", ex);
5910  }
5911  throw ex;
5912  }
5913  }
5914 
5915  private void setLingerOption(LingerOption lref)
5916  {
5917  Linger linger = default(Linger);
5918  linger.OnOff = (ushort)(lref.Enabled ? 1 : 0);
5919  linger.Time = (ushort)lref.LingerTime;
5920  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(m_Handle, SocketOptionLevel.Socket, SocketOptionName.Linger, ref linger, 4);
5921  if (socketError == SocketError.SocketError)
5922  {
5923  SocketException ex = new SocketException();
5924  UpdateStatusAfterSocketError(ex);
5925  if (s_LoggingEnabled)
5926  {
5927  Logging.Exception(Logging.Sockets, this, "setLingerOption", ex);
5928  }
5929  throw ex;
5930  }
5931  }
5932 
5933  private LingerOption getLingerOpt()
5934  {
5935  Linger optionValue = default(Linger);
5936  int optionLength = 4;
5937  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.getsockopt(m_Handle, SocketOptionLevel.Socket, SocketOptionName.Linger, out optionValue, ref optionLength);
5938  if (socketError == SocketError.SocketError)
5939  {
5940  SocketException ex = new SocketException();
5941  UpdateStatusAfterSocketError(ex);
5942  if (s_LoggingEnabled)
5943  {
5944  Logging.Exception(Logging.Sockets, this, "getLingerOpt", ex);
5945  }
5946  throw ex;
5947  }
5948  return new LingerOption(optionValue.OnOff != 0, optionValue.Time);
5949  }
5950 
5951  private MulticastOption getMulticastOpt(SocketOptionName optionName)
5952  {
5953  IPMulticastRequest optionValue = default(IPMulticastRequest);
5954  int optionLength = IPMulticastRequest.Size;
5955  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.getsockopt(m_Handle, SocketOptionLevel.IP, optionName, out optionValue, ref optionLength);
5956  if (socketError == SocketError.SocketError)
5957  {
5958  SocketException ex = new SocketException();
5959  UpdateStatusAfterSocketError(ex);
5960  if (s_LoggingEnabled)
5961  {
5962  Logging.Exception(Logging.Sockets, this, "getMulticastOpt", ex);
5963  }
5964  throw ex;
5965  }
5966  IPAddress group = new IPAddress(optionValue.MulticastAddress);
5967  IPAddress mcint = new IPAddress(optionValue.InterfaceAddress);
5968  return new MulticastOption(group, mcint);
5969  }
5970 
5971  private IPv6MulticastOption getIPv6MulticastOpt(SocketOptionName optionName)
5972  {
5973  IPv6MulticastRequest optionValue = default(IPv6MulticastRequest);
5974  int optionLength = IPv6MulticastRequest.Size;
5975  SocketError socketError = UnsafeNclNativeMethods.OSSOCK.getsockopt(m_Handle, SocketOptionLevel.IP, optionName, out optionValue, ref optionLength);
5976  if (socketError == SocketError.SocketError)
5977  {
5978  SocketException ex = new SocketException();
5979  UpdateStatusAfterSocketError(ex);
5980  if (s_LoggingEnabled)
5981  {
5982  Logging.Exception(Logging.Sockets, this, "getIPv6MulticastOpt", ex);
5983  }
5984  throw ex;
5985  }
5986  return new IPv6MulticastOption(new IPAddress(optionValue.MulticastAddress), optionValue.InterfaceIndex);
5987  }
5988 
5989  private SocketError InternalSetBlocking(bool desired, out bool current)
5990  {
5991  if (CleanedUp)
5992  {
5993  current = willBlock;
5994  return SocketError.Success;
5995  }
5996  int argp = (!desired) ? (-1) : 0;
5997  SocketError socketError;
5998  try
5999  {
6000  socketError = UnsafeNclNativeMethods.OSSOCK.ioctlsocket(m_Handle, -2147195266, ref argp);
6001  if (socketError == SocketError.SocketError)
6002  {
6003  socketError = (SocketError)Marshal.GetLastWin32Error();
6004  }
6005  }
6006  catch (ObjectDisposedException)
6007  {
6008  socketError = SocketError.NotSocket;
6009  }
6010  if (socketError == SocketError.Success)
6011  {
6012  willBlockInternal = (argp == 0);
6013  }
6014  current = willBlockInternal;
6015  return socketError;
6016  }
6017 
6018  internal void InternalSetBlocking(bool desired)
6019  {
6020  InternalSetBlocking(desired, out bool _);
6021  }
6022 
6023  private static IntPtr[] SocketListToFileDescriptorSet(IList socketList)
6024  {
6025  if (socketList == null || socketList.Count == 0)
6026  {
6027  return null;
6028  }
6029  IntPtr[] array = new IntPtr[socketList.Count + 1];
6030  array[0] = (IntPtr)socketList.Count;
6031  for (int i = 0; i < socketList.Count; i++)
6032  {
6033  if (!(socketList[i] is Socket))
6034  {
6035  throw new ArgumentException(SR.GetString("net_sockets_select", socketList[i].GetType().FullName, typeof(Socket).FullName), "socketList");
6036  }
6037  array[i + 1] = ((Socket)socketList[i]).m_Handle.DangerousGetHandle();
6038  }
6039  return array;
6040  }
6041 
6042  private static void SelectFileDescriptor(IList socketList, IntPtr[] fileDescriptorSet)
6043  {
6044  if (socketList != null && socketList.Count != 0)
6045  {
6046  if ((int)fileDescriptorSet[0] == 0)
6047  {
6048  socketList.Clear();
6049  }
6050  else
6051  {
6052  lock (socketList)
6053  {
6054  for (int i = 0; i < socketList.Count; i++)
6055  {
6056  Socket socket = socketList[i] as Socket;
6057  int j;
6058  for (j = 0; j < (int)fileDescriptorSet[0] && !(fileDescriptorSet[j + 1] == socket.m_Handle.DangerousGetHandle()); j++)
6059  {
6060  }
6061  if (j == (int)fileDescriptorSet[0])
6062  {
6063  socketList.RemoveAt(i--);
6064  }
6065  }
6066  }
6067  }
6068  }
6069  }
6070 
6071  private static void MicrosecondsToTimeValue(long microSeconds, ref TimeValue socketTime)
6072  {
6073  socketTime.Seconds = (int)(microSeconds / 1000000);
6074  socketTime.Microseconds = (int)(microSeconds % 1000000);
6075  }
6076 
6077  private IAsyncResult BeginConnectEx(EndPoint remoteEP, bool flowContext, AsyncCallback callback, object state)
6078  {
6079  if (s_LoggingEnabled)
6080  {
6081  Logging.Enter(Logging.Sockets, this, "BeginConnectEx", "");
6082  }
6083  EndPoint remoteEP2 = remoteEP;
6084  SocketAddress socketAddress = flowContext ? CheckCacheRemote(ref remoteEP2, isOverwrite: true) : SnapshotAndSerialize(ref remoteEP2);
6085  if (m_RightEndPoint == null)
6086  {
6087  if (remoteEP2.AddressFamily == AddressFamily.InterNetwork)
6088  {
6089  InternalBind(new IPEndPoint(IPAddress.Any, 0));
6090  }
6091  else
6092  {
6093  InternalBind(new IPEndPoint(IPAddress.IPv6Any, 0));
6094  }
6095  }
6096  ConnectOverlappedAsyncResult connectOverlappedAsyncResult = new ConnectOverlappedAsyncResult(this, remoteEP2, state, callback);
6097  if (flowContext)
6098  {
6099  connectOverlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
6100  }
6101  connectOverlappedAsyncResult.SetUnmanagedStructures(socketAddress.m_Buffer);
6102  EndPoint rightEndPoint = m_RightEndPoint;
6103  if (m_RightEndPoint == null)
6104  {
6105  m_RightEndPoint = remoteEP2;
6106  }
6107  SocketError socketError = SocketError.Success;
6108  try
6109  {
6110  if (!ConnectEx(m_Handle, Marshal.UnsafeAddrOfPinnedArrayElement((Array)socketAddress.m_Buffer, 0), socketAddress.m_Size, IntPtr.Zero, 0, out int _, connectOverlappedAsyncResult.OverlappedHandle))
6111  {
6112  socketError = (SocketError)Marshal.GetLastWin32Error();
6113  }
6114  }
6115  catch
6116  {
6117  connectOverlappedAsyncResult.InternalCleanup();
6118  m_RightEndPoint = rightEndPoint;
6119  throw;
6120  }
6121  if (socketError == SocketError.Success)
6122  {
6123  SetToConnected();
6124  }
6125  socketError = connectOverlappedAsyncResult.CheckAsyncCallOverlappedResult(socketError);
6126  if (socketError != 0)
6127  {
6128  m_RightEndPoint = rightEndPoint;
6129  SocketException ex = new SocketException(socketError);
6130  UpdateStatusAfterSocketError(ex);
6131  if (s_LoggingEnabled)
6132  {
6133  Logging.Exception(Logging.Sockets, this, "BeginConnectEx", ex);
6134  }
6135  throw ex;
6136  }
6137  connectOverlappedAsyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
6138  if (s_LoggingEnabled)
6139  {
6140  Logging.Exit(Logging.Sockets, this, "BeginConnectEx", connectOverlappedAsyncResult);
6141  }
6142  return connectOverlappedAsyncResult;
6143  }
6144 
6145  internal void MultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags)
6146  {
6147  if (s_LoggingEnabled)
6148  {
6149  Logging.Enter(Logging.Sockets, this, "MultipleSend", "");
6150  }
6151  if (CleanedUp)
6152  {
6153  throw new ObjectDisposedException(GetType().FullName);
6154  }
6155  WSABuffer[] array = new WSABuffer[buffers.Length];
6156  GCHandle[] array2 = null;
6157  SocketError socketError;
6158  try
6159  {
6160  array2 = new GCHandle[buffers.Length];
6161  for (int i = 0; i < buffers.Length; i++)
6162  {
6163  array2[i] = GCHandle.Alloc(buffers[i].Buffer, GCHandleType.Pinned);
6164  array[i].Length = buffers[i].Size;
6165  array[i].Pointer = Marshal.UnsafeAddrOfPinnedArrayElement((Array)buffers[i].Buffer, buffers[i].Offset);
6166  }
6167  socketError = UnsafeNclNativeMethods.OSSOCK.WSASend_Blocking(m_Handle.DangerousGetHandle(), array, array.Length, out int _, socketFlags, SafeNativeOverlapped.Zero, IntPtr.Zero);
6168  }
6169  finally
6170  {
6171  if (array2 != null)
6172  {
6173  for (int j = 0; j < array2.Length; j++)
6174  {
6175  if (array2[j].IsAllocated)
6176  {
6177  array2[j].Free();
6178  }
6179  }
6180  }
6181  }
6182  if (socketError != 0)
6183  {
6184  SocketException ex = new SocketException();
6185  UpdateStatusAfterSocketError(ex);
6186  if (s_LoggingEnabled)
6187  {
6188  Logging.Exception(Logging.Sockets, this, "MultipleSend", ex);
6189  }
6190  throw ex;
6191  }
6192  if (s_LoggingEnabled)
6193  {
6194  Logging.Exit(Logging.Sockets, this, "MultipleSend", "");
6195  }
6196  }
6197 
6198  private static void DnsCallback(IAsyncResult result)
6199  {
6200  if (!result.CompletedSynchronously)
6201  {
6202  bool flag = false;
6203  MultipleAddressConnectAsyncResult multipleAddressConnectAsyncResult = (MultipleAddressConnectAsyncResult)result.AsyncState;
6204  try
6205  {
6206  flag = DoDnsCallback(result, multipleAddressConnectAsyncResult);
6207  }
6208  catch (Exception result2)
6209  {
6210  multipleAddressConnectAsyncResult.InvokeCallback(result2);
6211  }
6212  if (flag)
6213  {
6214  multipleAddressConnectAsyncResult.InvokeCallback();
6215  }
6216  }
6217  }
6218 
6219  private static bool DoDnsCallback(IAsyncResult result, MultipleAddressConnectAsyncResult context)
6220  {
6221  IPAddress[] array = context.addresses = Dns.EndGetHostAddresses(result);
6222  return DoMultipleAddressConnectCallback(PostOneBeginConnect(context), context);
6223  }
6224 
6225  private static object PostOneBeginConnect(MultipleAddressConnectAsyncResult context)
6226  {
6227  IPAddress iPAddress = context.addresses[context.index];
6228  if (!context.socket.CanTryAddressFamily(iPAddress.AddressFamily))
6229  {
6230  if (context.lastException == null)
6231  {
6232  return new ArgumentException(SR.GetString("net_invalidAddressList"), "context");
6233  }
6234  return context.lastException;
6235  }
6236  try
6237  {
6238  EndPoint remoteEP = new IPEndPoint(iPAddress, context.port);
6239  context.socket.CheckCacheRemote(ref remoteEP, isOverwrite: true);
6240  IAsyncResult asyncResult = context.socket.UnsafeBeginConnect(remoteEP, MultipleAddressConnectCallback, context);
6241  if (asyncResult.CompletedSynchronously)
6242  {
6243  return asyncResult;
6244  }
6245  }
6246  catch (Exception ex)
6247  {
6248  if (ex is OutOfMemoryException || ex is StackOverflowException || ex is ThreadAbortException)
6249  {
6250  throw;
6251  }
6252  return ex;
6253  }
6254  return null;
6255  }
6256 
6257  private static void MultipleAddressConnectCallback(IAsyncResult result)
6258  {
6259  if (!result.CompletedSynchronously)
6260  {
6261  bool flag = false;
6262  MultipleAddressConnectAsyncResult multipleAddressConnectAsyncResult = (MultipleAddressConnectAsyncResult)result.AsyncState;
6263  try
6264  {
6265  flag = DoMultipleAddressConnectCallback(result, multipleAddressConnectAsyncResult);
6266  }
6267  catch (Exception result2)
6268  {
6269  multipleAddressConnectAsyncResult.InvokeCallback(result2);
6270  }
6271  if (flag)
6272  {
6273  multipleAddressConnectAsyncResult.InvokeCallback();
6274  }
6275  }
6276  }
6277 
6278  private static bool DoMultipleAddressConnectCallback(object result, MultipleAddressConnectAsyncResult context)
6279  {
6280  while (result != null)
6281  {
6282  Exception ex = result as Exception;
6283  if (ex == null)
6284  {
6285  try
6286  {
6287  context.socket.EndConnect((IAsyncResult)result);
6288  }
6289  catch (Exception ex2)
6290  {
6291  ex = ex2;
6292  }
6293  }
6294  if (ex == null)
6295  {
6296  return true;
6297  }
6298  if (++context.index >= context.addresses.Length)
6299  {
6300  throw ex;
6301  }
6302  context.lastException = ex;
6303  result = PostOneBeginConnect(context);
6304  }
6305  return false;
6306  }
6307 
6308  internal IAsyncResult BeginMultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
6309  {
6310  OverlappedAsyncResult overlappedAsyncResult = new OverlappedAsyncResult(this, state, callback);
6311  overlappedAsyncResult.StartPostingAsyncOp(lockCapture: false);
6312  DoBeginMultipleSend(buffers, socketFlags, overlappedAsyncResult);
6313  overlappedAsyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
6314  return overlappedAsyncResult;
6315  }
6316 
6317  internal IAsyncResult UnsafeBeginMultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
6318  {
6319  OverlappedAsyncResult overlappedAsyncResult = new OverlappedAsyncResult(this, state, callback);
6320  DoBeginMultipleSend(buffers, socketFlags, overlappedAsyncResult);
6321  return overlappedAsyncResult;
6322  }
6323 
6324  private void DoBeginMultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
6325  {
6326  if (s_LoggingEnabled)
6327  {
6328  Logging.Enter(Logging.Sockets, this, "BeginMultipleSend", "");
6329  }
6330  if (CleanedUp)
6331  {
6332  throw new ObjectDisposedException(GetType().FullName);
6333  }
6334  SocketError socketError = SocketError.SocketError;
6335  try
6336  {
6337  asyncResult.SetUnmanagedStructures(buffers, ref Caches.SendOverlappedCache);
6338  socketError = UnsafeNclNativeMethods.OSSOCK.WSASend(m_Handle, asyncResult.m_WSABuffers, asyncResult.m_WSABuffers.Length, out int _, socketFlags, asyncResult.OverlappedHandle, IntPtr.Zero);
6339  if (socketError != 0)
6340  {
6341  socketError = (SocketError)Marshal.GetLastWin32Error();
6342  }
6343  }
6344  finally
6345  {
6346  socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
6347  }
6348  if (socketError != 0)
6349  {
6350  asyncResult.ExtractCache(ref Caches.SendOverlappedCache);
6351  SocketException ex = new SocketException(socketError);
6352  UpdateStatusAfterSocketError(ex);
6353  if (s_LoggingEnabled)
6354  {
6355  Logging.Exception(Logging.Sockets, this, "BeginMultipleSend", ex);
6356  }
6357  throw ex;
6358  }
6359  if (s_LoggingEnabled)
6360  {
6361  Logging.Exit(Logging.Sockets, this, "BeginMultipleSend", asyncResult);
6362  }
6363  }
6364 
6365  internal int EndMultipleSend(IAsyncResult asyncResult)
6366  {
6367  if (s_LoggingEnabled)
6368  {
6369  Logging.Enter(Logging.Sockets, this, "EndMultipleSend", asyncResult);
6370  }
6371  OverlappedAsyncResult overlappedAsyncResult = asyncResult as OverlappedAsyncResult;
6372  int num = (int)overlappedAsyncResult.InternalWaitForCompletion();
6373  overlappedAsyncResult.EndCalled = true;
6374  overlappedAsyncResult.ExtractCache(ref Caches.SendOverlappedCache);
6375  if (s_PerfCountersEnabled && num > 0)
6376  {
6377  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, num);
6378  if (Transport == TransportType.Udp)
6379  {
6380  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
6381  }
6382  }
6383  if (overlappedAsyncResult.ErrorCode != 0)
6384  {
6385  SocketException ex = new SocketException(overlappedAsyncResult.ErrorCode);
6386  if (s_LoggingEnabled)
6387  {
6388  Logging.Exception(Logging.Sockets, this, "EndMultipleSend", ex);
6389  }
6390  throw ex;
6391  }
6392  if (s_LoggingEnabled)
6393  {
6394  Logging.Exit(Logging.Sockets, this, "EndMultipleSend", num);
6395  }
6396  return num;
6397  }
6398 
6399  private Socket CreateAcceptSocket(SafeCloseSocket fd, EndPoint remoteEP, bool needCancelSelect)
6400  {
6401  Socket socket = new Socket(fd);
6402  return UpdateAcceptSocket(socket, remoteEP, needCancelSelect);
6403  }
6404 
6405  internal Socket UpdateAcceptSocket(Socket socket, EndPoint remoteEP, bool needCancelSelect)
6406  {
6407  socket.addressFamily = addressFamily;
6408  socket.socketType = socketType;
6409  socket.protocolType = protocolType;
6410  socket.m_RightEndPoint = m_RightEndPoint;
6411  socket.m_RemoteEndPoint = remoteEP;
6412  socket.SetToConnected();
6413  socket.willBlock = willBlock;
6414  if (needCancelSelect)
6415  {
6416  socket.UnsetAsyncEventSelect();
6417  }
6418  else
6419  {
6420  socket.InternalSetBlocking(willBlock);
6421  }
6422  return socket;
6423  }
6424 
6425  internal void SetToConnected()
6426  {
6427  if (!m_IsConnected)
6428  {
6429  m_IsConnected = true;
6430  m_IsDisconnected = false;
6431  if (s_PerfCountersEnabled)
6432  {
6433  NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketConnectionsEstablished);
6434  }
6435  }
6436  }
6437 
6438  internal void SetToDisconnected()
6439  {
6440  if (m_IsConnected)
6441  {
6442  m_IsConnected = false;
6443  m_IsDisconnected = true;
6444  if (!CleanedUp)
6445  {
6446  UnsetAsyncEventSelect();
6447  }
6448  }
6449  }
6450 
6451  internal void UpdateStatusAfterSocketError(SocketException socketException)
6452  {
6453  UpdateStatusAfterSocketError((SocketError)socketException.NativeErrorCode);
6454  }
6455 
6456  internal void UpdateStatusAfterSocketError(SocketError errorCode)
6457  {
6458  if (s_LoggingEnabled)
6459  {
6460  Logging.PrintError(Logging.Sockets, this, "UpdateStatusAfterSocketError", errorCode.ToString());
6461  }
6462  if (m_IsConnected && (m_Handle.IsInvalid || (errorCode != SocketError.WouldBlock && errorCode != SocketError.IOPending && errorCode != SocketError.NoBufferSpaceAvailable && errorCode != SocketError.TimedOut)))
6463  {
6464  SetToDisconnected();
6465  }
6466  }
6467 
6468  private void UnsetAsyncEventSelect()
6469  {
6470  RegisteredWaitHandle registeredWait = m_RegisteredWait;
6471  if (registeredWait != null)
6472  {
6473  m_RegisteredWait = null;
6474  registeredWait.Unregister(null);
6475  }
6476  SocketError socketError = SocketError.NotSocket;
6477  try
6478  {
6479  socketError = UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(m_Handle, IntPtr.Zero, AsyncEventBits.FdNone);
6480  }
6481  catch (Exception exception)
6482  {
6483  if (NclUtilities.IsFatal(exception))
6484  {
6485  throw;
6486  }
6487  }
6488  if (m_AsyncEvent != null)
6489  {
6490  try
6491  {
6492  m_AsyncEvent.Reset();
6493  }
6494  catch (ObjectDisposedException)
6495  {
6496  }
6497  }
6498  if (socketError == SocketError.SocketError)
6499  {
6500  UpdateStatusAfterSocketError(socketError);
6501  }
6502  InternalSetBlocking(willBlock);
6503  }
6504 
6505  private bool SetAsyncEventSelect(AsyncEventBits blockEventBits)
6506  {
6507  if (m_RegisteredWait != null)
6508  {
6509  return false;
6510  }
6511  if (m_AsyncEvent == null)
6512  {
6513  Interlocked.CompareExchange(ref m_AsyncEvent, new ManualResetEvent(initialState: false), null);
6514  if (s_RegisteredWaitCallback == null)
6515  {
6516  s_RegisteredWaitCallback = RegisteredWaitCallback;
6517  }
6518  }
6519  if (Interlocked.CompareExchange(ref m_IntCleanedUp, 2, 0) != 0)
6520  {
6521  return false;
6522  }
6523  try
6524  {
6525  m_BlockEventBits = blockEventBits;
6526  m_RegisteredWait = ThreadPool.UnsafeRegisterWaitForSingleObject(m_AsyncEvent, s_RegisteredWaitCallback, this, -1, executeOnlyOnce: true);
6527  }
6528  finally
6529  {
6530  Interlocked.Exchange(ref m_IntCleanedUp, 0);
6531  }
6532  SocketError socketError = SocketError.NotSocket;
6533  try
6534  {
6535  socketError = UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(m_Handle, m_AsyncEvent.SafeWaitHandle, blockEventBits);
6536  }
6537  catch (Exception exception)
6538  {
6539  if (NclUtilities.IsFatal(exception))
6540  {
6541  throw;
6542  }
6543  }
6544  if (socketError == SocketError.SocketError)
6545  {
6546  UpdateStatusAfterSocketError(socketError);
6547  }
6548  willBlockInternal = false;
6549  return socketError == SocketError.Success;
6550  }
6551 
6552  private static void RegisteredWaitCallback(object state, bool timedOut)
6553  {
6554  Socket socket = (Socket)state;
6555  if (Interlocked.Exchange(ref socket.m_RegisteredWait, null) != null)
6556  {
6557  switch (socket.m_BlockEventBits)
6558  {
6559  case AsyncEventBits.FdConnect:
6560  socket.ConnectCallback();
6561  break;
6562  case AsyncEventBits.FdAccept:
6563  socket.AcceptCallback(null);
6564  break;
6565  }
6566  }
6567  }
6568 
6569  private void ValidateBlockingMode()
6570  {
6571  if (willBlock && !willBlockInternal)
6572  {
6573  throw new InvalidOperationException(SR.GetString("net_invasync"));
6574  }
6575  }
6576 
6577  [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.UnmanagedCode)]
6578  internal void BindToCompletionPort()
6579  {
6580  if (!m_BoundToThreadPool && !UseOverlappedIO)
6581  {
6582  lock (this)
6583  {
6584  if (!m_BoundToThreadPool)
6585  {
6586  try
6587  {
6588  ThreadPool.BindHandle(m_Handle);
6589  m_BoundToThreadPool = true;
6590  }
6591  catch (Exception exception)
6592  {
6593  if (NclUtilities.IsFatal(exception))
6594  {
6595  throw;
6596  }
6597  Close(0);
6598  throw;
6599  }
6600  }
6601  }
6602  }
6603  }
6604 
6615  {
6616  if (s_LoggingEnabled)
6617  {
6618  Logging.Enter(Logging.Sockets, this, "AcceptAsync", "");
6619  }
6620  if (CleanedUp)
6621  {
6622  throw new ObjectDisposedException(GetType().FullName);
6623  }
6624  if (e.m_BufferList != null)
6625  {
6626  throw new ArgumentException(SR.GetString("net_multibuffernotsupported"), "BufferList");
6627  }
6628  if (m_RightEndPoint == null)
6629  {
6630  throw new InvalidOperationException(SR.GetString("net_sockets_mustbind"));
6631  }
6632  if (!isListening)
6633  {
6634  throw new InvalidOperationException(SR.GetString("net_sockets_mustlisten"));
6635  }
6636  if (e.AcceptSocket == null)
6637  {
6638  e.AcceptSocket = new Socket(addressFamily, socketType, protocolType);
6639  }
6640  else if (e.AcceptSocket.m_RightEndPoint != null && !e.AcceptSocket.m_IsDisconnected)
6641  {
6642  throw new InvalidOperationException(SR.GetString("net_sockets_namedmustnotbebound", "AcceptSocket"));
6643  }
6644  e.StartOperationCommon(this);
6645  e.StartOperationAccept();
6646  BindToCompletionPort();
6647  SocketError socketError = SocketError.Success;
6648  int bytesReceived;
6649  try
6650  {
6651  if (!AcceptEx(m_Handle, e.AcceptSocket.m_Handle, (e.m_PtrSingleBuffer != IntPtr.Zero) ? e.m_PtrSingleBuffer : e.m_PtrAcceptBuffer, (e.m_PtrSingleBuffer != IntPtr.Zero) ? (e.Count - e.m_AcceptAddressBufferCount) : 0, e.m_AcceptAddressBufferCount / 2, e.m_AcceptAddressBufferCount / 2, out bytesReceived, e.m_PtrNativeOverlapped))
6652  {
6653  socketError = (SocketError)Marshal.GetLastWin32Error();
6654  }
6655  }
6656  catch (Exception ex)
6657  {
6658  e.Complete();
6659  throw ex;
6660  }
6661  bool flag;
6662  if (socketError != 0 && socketError != SocketError.IOPending)
6663  {
6664  e.FinishOperationSyncFailure(socketError, bytesReceived, SocketFlags.None);
6665  flag = false;
6666  }
6667  else
6668  {
6669  flag = true;
6670  }
6671  if (s_LoggingEnabled)
6672  {
6673  Logging.Exit(Logging.Sockets, this, "AcceptAsync", flag);
6674  }
6675  return flag;
6676  }
6677 
6689  {
6690  if (s_LoggingEnabled)
6691  {
6692  Logging.Enter(Logging.Sockets, this, "ConnectAsync", "");
6693  }
6694  if (CleanedUp)
6695  {
6696  throw new ObjectDisposedException(GetType().FullName);
6697  }
6698  if (e.m_BufferList != null)
6699  {
6700  throw new ArgumentException(SR.GetString("net_multibuffernotsupported"), "BufferList");
6701  }
6702  if (e.RemoteEndPoint == null)
6703  {
6704  throw new ArgumentNullException("remoteEP");
6705  }
6706  if (isListening)
6707  {
6708  throw new InvalidOperationException(SR.GetString("net_sockets_mustnotlisten"));
6709  }
6710  EndPoint remoteEP = e.RemoteEndPoint;
6711  DnsEndPoint dnsEndPoint = remoteEP as DnsEndPoint;
6712  bool flag;
6713  if (dnsEndPoint != null)
6714  {
6715  if (s_LoggingEnabled)
6716  {
6717  Logging.PrintInfo(Logging.Sockets, "Socket#" + ValidationHelper.HashString(this) + "::ConnectAsync " + SR.GetString("net_log_socket_connect_dnsendpoint"));
6718  }
6719  if (dnsEndPoint.AddressFamily != 0 && !CanTryAddressFamily(dnsEndPoint.AddressFamily))
6720  {
6721  throw new NotSupportedException(SR.GetString("net_invalidversion"));
6722  }
6723  MultipleConnectAsync multipleConnectAsync = new SingleSocketMultipleConnectAsync(this, userSocket: true);
6724  e.StartOperationCommon(this);
6725  e.StartOperationWrapperConnect(multipleConnectAsync);
6726  flag = multipleConnectAsync.StartConnectAsync(e, dnsEndPoint);
6727  }
6728  else
6729  {
6730  if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily))
6731  {
6732  throw new NotSupportedException(SR.GetString("net_invalidversion"));
6733  }
6734  e.m_SocketAddress = CheckCacheRemote(ref remoteEP, isOverwrite: false);
6735  if (m_RightEndPoint == null)
6736  {
6737  if (remoteEP.AddressFamily == AddressFamily.InterNetwork)
6738  {
6739  InternalBind(new IPEndPoint(IPAddress.Any, 0));
6740  }
6741  else
6742  {
6743  InternalBind(new IPEndPoint(IPAddress.IPv6Any, 0));
6744  }
6745  }
6746  EndPoint rightEndPoint = m_RightEndPoint;
6747  if (m_RightEndPoint == null)
6748  {
6749  m_RightEndPoint = remoteEP;
6750  }
6751  e.StartOperationCommon(this);
6752  e.StartOperationConnect();
6753  BindToCompletionPort();
6754  SocketError socketError = SocketError.Success;
6755  int bytesSent;
6756  try
6757  {
6758  if (!ConnectEx(m_Handle, e.m_PtrSocketAddressBuffer, e.m_SocketAddress.m_Size, e.m_PtrSingleBuffer, e.Count, out bytesSent, e.m_PtrNativeOverlapped))
6759  {
6760  socketError = (SocketError)Marshal.GetLastWin32Error();
6761  }
6762  }
6763  catch (Exception ex)
6764  {
6765  m_RightEndPoint = rightEndPoint;
6766  e.Complete();
6767  throw ex;
6768  }
6769  if (socketError != 0 && socketError != SocketError.IOPending)
6770  {
6771  e.FinishOperationSyncFailure(socketError, bytesSent, SocketFlags.None);
6772  flag = false;
6773  }
6774  else
6775  {
6776  flag = true;
6777  }
6778  }
6779  if (s_LoggingEnabled)
6780  {
6781  Logging.Exit(Logging.Sockets, this, "ConnectAsync", flag);
6782  }
6783  return flag;
6784  }
6785 
6798  public static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
6799  {
6800  if (s_LoggingEnabled)
6801  {
6802  Logging.Enter(Logging.Sockets, null, "ConnectAsync", "");
6803  }
6804  if (e.m_BufferList != null)
6805  {
6806  throw new ArgumentException(SR.GetString("net_multibuffernotsupported"), "BufferList");
6807  }
6808  if (e.RemoteEndPoint == null)
6809  {
6810  throw new ArgumentNullException("remoteEP");
6811  }
6812  EndPoint remoteEndPoint = e.RemoteEndPoint;
6813  DnsEndPoint dnsEndPoint = remoteEndPoint as DnsEndPoint;
6814  bool flag;
6815  if (dnsEndPoint != null)
6816  {
6817  Socket socket = null;
6818  MultipleConnectAsync multipleConnectAsync = null;
6819  if (dnsEndPoint.AddressFamily == AddressFamily.Unspecified)
6820  {
6821  multipleConnectAsync = new MultipleSocketMultipleConnectAsync(socketType, protocolType);
6822  }
6823  else
6824  {
6825  socket = new Socket(dnsEndPoint.AddressFamily, socketType, protocolType);
6826  multipleConnectAsync = new SingleSocketMultipleConnectAsync(socket, userSocket: false);
6827  }
6828  e.StartOperationCommon(socket);
6829  e.StartOperationWrapperConnect(multipleConnectAsync);
6830  flag = multipleConnectAsync.StartConnectAsync(e, dnsEndPoint);
6831  }
6832  else
6833  {
6834  Socket socket2 = new Socket(remoteEndPoint.AddressFamily, socketType, protocolType);
6835  flag = socket2.ConnectAsync(e);
6836  }
6837  if (s_LoggingEnabled)
6838  {
6839  Logging.Exit(Logging.Sockets, null, "ConnectAsync", flag);
6840  }
6841  return flag;
6842  }
6843 
6851  {
6852  if (e == null)
6853  {
6854  throw new ArgumentNullException("e");
6855  }
6856  e.CancelConnectAsync();
6857  }
6858 
6868  {
6869  if (s_LoggingEnabled)
6870  {
6871  Logging.Enter(Logging.Sockets, this, "DisconnectAsync", "");
6872  }
6873  if (CleanedUp)
6874  {
6875  throw new ObjectDisposedException(GetType().FullName);
6876  }
6877  e.StartOperationCommon(this);
6878  e.StartOperationDisconnect();
6879  BindToCompletionPort();
6880  SocketError socketError = SocketError.Success;
6881  try
6882  {
6883  if (!DisconnectEx(m_Handle, e.m_PtrNativeOverlapped, e.DisconnectReuseSocket ? 2 : 0, 0))
6884  {
6885  socketError = (SocketError)Marshal.GetLastWin32Error();
6886  }
6887  }
6888  catch (Exception ex)
6889  {
6890  e.Complete();
6891  throw ex;
6892  }
6893  bool flag;
6894  if (socketError != 0 && socketError != SocketError.IOPending)
6895  {
6896  e.FinishOperationSyncFailure(socketError, 0, SocketFlags.None);
6897  flag = false;
6898  }
6899  else
6900  {
6901  flag = true;
6902  }
6903  if (s_LoggingEnabled)
6904  {
6905  Logging.Exit(Logging.Sockets, this, "DisconnectAsync", flag);
6906  }
6907  return flag;
6908  }
6909 
6919  {
6920  if (s_LoggingEnabled)
6921  {
6922  Logging.Enter(Logging.Sockets, this, "ReceiveAsync", "");
6923  }
6924  if (CleanedUp)
6925  {
6926  throw new ObjectDisposedException(GetType().FullName);
6927  }
6928  e.StartOperationCommon(this);
6929  e.StartOperationReceive();
6930  BindToCompletionPort();
6931  SocketFlags socketFlags = e.m_SocketFlags;
6932  SocketError socketError;
6933  int bytesTransferred;
6934  try
6935  {
6936  socketError = ((e.m_Buffer == null) ? UnsafeNclNativeMethods.OSSOCK.WSARecv(m_Handle, e.m_WSABufferArray, e.m_WSABufferArray.Length, out bytesTransferred, ref socketFlags, e.m_PtrNativeOverlapped, IntPtr.Zero) : UnsafeNclNativeMethods.OSSOCK.WSARecv(m_Handle, ref e.m_WSABuffer, 1, out bytesTransferred, ref socketFlags, e.m_PtrNativeOverlapped, IntPtr.Zero));
6937  }
6938  catch (Exception ex)
6939  {
6940  e.Complete();
6941  throw ex;
6942  }
6943  if (socketError != 0)
6944  {
6945  socketError = (SocketError)Marshal.GetLastWin32Error();
6946  }
6947  bool flag;
6948  if (socketError != 0 && socketError != SocketError.IOPending)
6949  {
6950  e.FinishOperationSyncFailure(socketError, bytesTransferred, socketFlags);
6951  flag = false;
6952  }
6953  else
6954  {
6955  flag = true;
6956  }
6957  if (s_LoggingEnabled)
6958  {
6959  Logging.Exit(Logging.Sockets, this, "ReceiveAsync", flag);
6960  }
6961  return flag;
6962  }
6963 
6973  {
6974  if (s_LoggingEnabled)
6975  {
6976  Logging.Enter(Logging.Sockets, this, "ReceiveFromAsync", "");
6977  }
6978  if (CleanedUp)
6979  {
6980  throw new ObjectDisposedException(GetType().FullName);
6981  }
6982  if (e.RemoteEndPoint == null)
6983  {
6984  throw new ArgumentNullException("RemoteEndPoint");
6985  }
6986  if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily))
6987  {
6988  throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", e.RemoteEndPoint.AddressFamily, addressFamily), "RemoteEndPoint");
6989  }
6990  EndPoint remoteEP = e.RemoteEndPoint;
6991  e.m_SocketAddress = SnapshotAndSerialize(ref remoteEP);
6992  e.RemoteEndPoint = remoteEP;
6993  e.StartOperationCommon(this);
6994  e.StartOperationReceiveFrom();
6995  BindToCompletionPort();
6996  SocketFlags socketFlags = e.m_SocketFlags;
6997  SocketError socketError;
6998  int bytesTransferred;
6999  try
7000  {
7001  socketError = ((e.m_Buffer == null) ? UnsafeNclNativeMethods.OSSOCK.WSARecvFrom(m_Handle, e.m_WSABufferArray, e.m_WSABufferArray.Length, out bytesTransferred, ref socketFlags, e.m_PtrSocketAddressBuffer, e.m_PtrSocketAddressBufferSize, e.m_PtrNativeOverlapped, IntPtr.Zero) : UnsafeNclNativeMethods.OSSOCK.WSARecvFrom(m_Handle, ref e.m_WSABuffer, 1, out bytesTransferred, ref socketFlags, e.m_PtrSocketAddressBuffer, e.m_PtrSocketAddressBufferSize, e.m_PtrNativeOverlapped, IntPtr.Zero));
7002  }
7003  catch (Exception ex)
7004  {
7005  e.Complete();
7006  throw ex;
7007  }
7008  if (socketError != 0)
7009  {
7010  socketError = (SocketError)Marshal.GetLastWin32Error();
7011  }
7012  bool flag;
7013  if (socketError != 0 && socketError != SocketError.IOPending)
7014  {
7015  e.FinishOperationSyncFailure(socketError, bytesTransferred, socketFlags);
7016  flag = false;
7017  }
7018  else
7019  {
7020  flag = true;
7021  }
7022  if (s_LoggingEnabled)
7023  {
7024  Logging.Exit(Logging.Sockets, this, "ReceiveFromAsync", flag);
7025  }
7026  return flag;
7027  }
7028 
7037  {
7038  if (s_LoggingEnabled)
7039  {
7040  Logging.Enter(Logging.Sockets, this, "ReceiveMessageFromAsync", "");
7041  }
7042  if (CleanedUp)
7043  {
7044  throw new ObjectDisposedException(GetType().FullName);
7045  }
7046  if (e.RemoteEndPoint == null)
7047  {
7048  throw new ArgumentNullException("RemoteEndPoint");
7049  }
7050  if (!CanTryAddressFamily(e.RemoteEndPoint.AddressFamily))
7051  {
7052  throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", e.RemoteEndPoint.AddressFamily, addressFamily), "RemoteEndPoint");
7053  }
7054  EndPoint remoteEP = e.RemoteEndPoint;
7055  e.m_SocketAddress = SnapshotAndSerialize(ref remoteEP);
7056  e.RemoteEndPoint = remoteEP;
7057  SetReceivingPacketInformation();
7058  e.StartOperationCommon(this);
7059  e.StartOperationReceiveMessageFrom();
7060  BindToCompletionPort();
7061  SocketError socketError;
7062  int bytesTransferred;
7063  try
7064  {
7065  socketError = WSARecvMsg(m_Handle, e.m_PtrWSAMessageBuffer, out bytesTransferred, e.m_PtrNativeOverlapped, IntPtr.Zero);
7066  }
7067  catch (Exception ex)
7068  {
7069  e.Complete();
7070  throw ex;
7071  }
7072  if (socketError != 0)
7073  {
7074  socketError = (SocketError)Marshal.GetLastWin32Error();
7075  }
7076  bool flag;
7077  if (socketError != 0 && socketError != SocketError.IOPending)
7078  {
7079  e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None);
7080  flag = false;
7081  }
7082  else
7083  {
7084  flag = true;
7085  }
7086  if (s_LoggingEnabled)
7087  {
7088  Logging.Exit(Logging.Sockets, this, "ReceiveMessageFromAsync", flag);
7089  }
7090  return flag;
7091  }
7092 
7102  {
7103  if (s_LoggingEnabled)
7104  {
7105  Logging.Enter(Logging.Sockets, this, "SendAsync", "");
7106  }
7107  if (CleanedUp)
7108  {
7109  throw new ObjectDisposedException(GetType().FullName);
7110  }
7111  e.StartOperationCommon(this);
7112  e.StartOperationSend();
7113  BindToCompletionPort();
7114  SocketError socketError;
7115  int bytesTransferred;
7116  try
7117  {
7118  socketError = ((e.m_Buffer == null) ? UnsafeNclNativeMethods.OSSOCK.WSASend(m_Handle, e.m_WSABufferArray, e.m_WSABufferArray.Length, out bytesTransferred, e.m_SocketFlags, e.m_PtrNativeOverlapped, IntPtr.Zero) : UnsafeNclNativeMethods.OSSOCK.WSASend(m_Handle, ref e.m_WSABuffer, 1, out bytesTransferred, e.m_SocketFlags, e.m_PtrNativeOverlapped, IntPtr.Zero));
7119  }
7120  catch (Exception ex)
7121  {
7122  e.Complete();
7123  throw ex;
7124  }
7125  if (socketError != 0)
7126  {
7127  socketError = (SocketError)Marshal.GetLastWin32Error();
7128  }
7129  bool flag;
7130  if (socketError != 0 && socketError != SocketError.IOPending)
7131  {
7132  e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None);
7133  flag = false;
7134  }
7135  else
7136  {
7137  flag = true;
7138  }
7139  if (s_LoggingEnabled)
7140  {
7141  Logging.Enter(Logging.Sockets, this, "SendAsync", flag);
7142  }
7143  return flag;
7144  }
7145 
7155  {
7156  if (s_LoggingEnabled)
7157  {
7158  Logging.Enter(Logging.Sockets, this, "SendPacketsAsync", "");
7159  }
7160  if (CleanedUp)
7161  {
7162  throw new ObjectDisposedException(GetType().FullName);
7163  }
7164  if (!Connected)
7165  {
7166  throw new NotSupportedException(SR.GetString("net_notconnected"));
7167  }
7168  e.StartOperationCommon(this);
7169  e.StartOperationSendPackets();
7170  BindToCompletionPort();
7171  bool flag2;
7172  if (e.m_SendPacketsDescriptor.Length != 0)
7173  {
7174  bool flag;
7175  try
7176  {
7177  flag = TransmitPackets(m_Handle, e.m_PtrSendPacketsDescriptor, e.m_SendPacketsDescriptor.Length, e.m_SendPacketsSendSize, e.m_PtrNativeOverlapped, e.m_SendPacketsFlags);
7178  }
7179  catch (Exception)
7180  {
7181  e.Complete();
7182  throw;
7183  }
7184  SocketError socketError = (SocketError)((!flag) ? Marshal.GetLastWin32Error() : 0);
7185  if (socketError != 0 && socketError != SocketError.IOPending)
7186  {
7187  e.FinishOperationSyncFailure(socketError, 0, SocketFlags.None);
7188  flag2 = false;
7189  }
7190  else
7191  {
7192  flag2 = true;
7193  }
7194  }
7195  else
7196  {
7197  e.FinishOperationSuccess(SocketError.Success, 0, SocketFlags.None);
7198  flag2 = false;
7199  }
7200  if (s_LoggingEnabled)
7201  {
7202  Logging.Exit(Logging.Sockets, this, "SendPacketsAsync", flag2);
7203  }
7204  return flag2;
7205  }
7206 
7216  {
7217  if (s_LoggingEnabled)
7218  {
7219  Logging.Enter(Logging.Sockets, this, "SendToAsync", "");
7220  }
7221  if (CleanedUp)
7222  {
7223  throw new ObjectDisposedException(GetType().FullName);
7224  }
7225  if (e.RemoteEndPoint == null)
7226  {
7227  throw new ArgumentNullException("RemoteEndPoint");
7228  }
7229  EndPoint remoteEP = e.RemoteEndPoint;
7230  e.m_SocketAddress = CheckCacheRemote(ref remoteEP, isOverwrite: false);
7231  e.StartOperationCommon(this);
7232  e.StartOperationSendTo();
7233  BindToCompletionPort();
7234  SocketError socketError;
7235  int bytesTransferred;
7236  try
7237  {
7238  socketError = ((e.m_Buffer == null) ? UnsafeNclNativeMethods.OSSOCK.WSASendTo(m_Handle, e.m_WSABufferArray, e.m_WSABufferArray.Length, out bytesTransferred, e.m_SocketFlags, e.m_PtrSocketAddressBuffer, e.m_SocketAddress.m_Size, e.m_PtrNativeOverlapped, IntPtr.Zero) : UnsafeNclNativeMethods.OSSOCK.WSASendTo(m_Handle, ref e.m_WSABuffer, 1, out bytesTransferred, e.m_SocketFlags, e.m_PtrSocketAddressBuffer, e.m_SocketAddress.m_Size, e.m_PtrNativeOverlapped, IntPtr.Zero));
7239  }
7240  catch (Exception ex)
7241  {
7242  e.Complete();
7243  throw ex;
7244  }
7245  if (socketError != 0)
7246  {
7247  socketError = (SocketError)Marshal.GetLastWin32Error();
7248  }
7249  bool flag;
7250  if (socketError != 0 && socketError != SocketError.IOPending)
7251  {
7252  e.FinishOperationSyncFailure(socketError, bytesTransferred, SocketFlags.None);
7253  flag = false;
7254  }
7255  else
7256  {
7257  flag = true;
7258  }
7259  if (s_LoggingEnabled)
7260  {
7261  Logging.Exit(Logging.Sockets, this, "SendToAsync", flag);
7262  }
7263  return flag;
7264  }
7265 
7266  internal Task<Socket> AcceptAsync(Socket acceptSocket)
7267  {
7268  TaskSocketAsyncEventArgs<Socket> taskSocketAsyncEventArgs = Interlocked.Exchange(ref LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs).Accept, s_rentedSocketSentinel);
7269  if (taskSocketAsyncEventArgs == s_rentedSocketSentinel)
7270  {
7271  return AcceptAsyncApm(acceptSocket);
7272  }
7273  if (taskSocketAsyncEventArgs == null)
7274  {
7275  taskSocketAsyncEventArgs = new TaskSocketAsyncEventArgs<Socket>();
7276  taskSocketAsyncEventArgs.Completed += AcceptCompletedHandler;
7277  }
7278  taskSocketAsyncEventArgs.AcceptSocket = acceptSocket;
7279  Task<Socket> result;
7280  if (AcceptAsync(taskSocketAsyncEventArgs))
7281  {
7282  result = taskSocketAsyncEventArgs.GetCompletionResponsibility(out bool responsibleForReturningToPool).Task;
7283  if (responsibleForReturningToPool)
7284  {
7285  ReturnSocketAsyncEventArgs(taskSocketAsyncEventArgs);
7286  }
7287  }
7288  else
7289  {
7290  result = ((taskSocketAsyncEventArgs.SocketError == SocketError.Success) ? Task.FromResult(taskSocketAsyncEventArgs.AcceptSocket) : Task.FromException<Socket>(GetException(taskSocketAsyncEventArgs.SocketError)));
7291  ReturnSocketAsyncEventArgs(taskSocketAsyncEventArgs);
7292  }
7293  return result;
7294  }
7295 
7296  private Task<Socket> AcceptAsyncApm(Socket acceptSocket)
7297  {
7298  TaskCompletionSource<Socket> taskCompletionSource = new TaskCompletionSource<Socket>(this);
7299  BeginAccept(acceptSocket, 0, delegate(IAsyncResult iar)
7300  {
7301  TaskCompletionSource<Socket> taskCompletionSource2 = (TaskCompletionSource<Socket>)iar.AsyncState;
7302  try
7303  {
7304  taskCompletionSource2.TrySetResult(((Socket)taskCompletionSource2.Task.AsyncState).EndAccept(iar));
7305  }
7306  catch (Exception exception)
7307  {
7308  taskCompletionSource2.TrySetException(exception);
7309  }
7310  }, taskCompletionSource);
7311  return taskCompletionSource.Task;
7312  }
7313 
7314  internal Task ConnectAsync(EndPoint remoteEP)
7315  {
7316  TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>(this);
7317  BeginConnect(remoteEP, delegate(IAsyncResult iar)
7318  {
7319  TaskCompletionSource<bool> taskCompletionSource2 = (TaskCompletionSource<bool>)iar.AsyncState;
7320  try
7321  {
7322  ((Socket)taskCompletionSource2.Task.AsyncState).EndConnect(iar);
7323  taskCompletionSource2.TrySetResult(result: true);
7324  }
7325  catch (Exception exception)
7326  {
7327  taskCompletionSource2.TrySetException(exception);
7328  }
7329  }, taskCompletionSource);
7330  return taskCompletionSource.Task;
7331  }
7332 
7333  internal Task ConnectAsync(IPAddress address, int port)
7334  {
7335  TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>(this);
7336  BeginConnect(address, port, delegate(IAsyncResult iar)
7337  {
7338  TaskCompletionSource<bool> taskCompletionSource2 = (TaskCompletionSource<bool>)iar.AsyncState;
7339  try
7340  {
7341  ((Socket)taskCompletionSource2.Task.AsyncState).EndConnect(iar);
7342  taskCompletionSource2.TrySetResult(result: true);
7343  }
7344  catch (Exception exception)
7345  {
7346  taskCompletionSource2.TrySetException(exception);
7347  }
7348  }, taskCompletionSource);
7349  return taskCompletionSource.Task;
7350  }
7351 
7352  internal Task ConnectAsync(IPAddress[] addresses, int port)
7353  {
7354  TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>(this);
7355  BeginConnect(addresses, port, delegate(IAsyncResult iar)
7356  {
7357  TaskCompletionSource<bool> taskCompletionSource2 = (TaskCompletionSource<bool>)iar.AsyncState;
7358  try
7359  {
7360  ((Socket)taskCompletionSource2.Task.AsyncState).EndConnect(iar);
7361  taskCompletionSource2.TrySetResult(result: true);
7362  }
7363  catch (Exception exception)
7364  {
7365  taskCompletionSource2.TrySetException(exception);
7366  }
7367  }, taskCompletionSource);
7368  return taskCompletionSource.Task;
7369  }
7370 
7371  internal Task ConnectAsync(string host, int port)
7372  {
7373  TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>(this);
7374  BeginConnect(host, port, delegate(IAsyncResult iar)
7375  {
7376  TaskCompletionSource<bool> taskCompletionSource2 = (TaskCompletionSource<bool>)iar.AsyncState;
7377  try
7378  {
7379  ((Socket)taskCompletionSource2.Task.AsyncState).EndConnect(iar);
7380  taskCompletionSource2.TrySetResult(result: true);
7381  }
7382  catch (Exception exception)
7383  {
7384  taskCompletionSource2.TrySetException(exception);
7385  }
7386  }, taskCompletionSource);
7387  return taskCompletionSource.Task;
7388  }
7389 
7390  internal Task<int> ReceiveAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream)
7391  {
7392  ValidateBuffer(buffer);
7393  Int32TaskSocketAsyncEventArgs int32TaskSocketAsyncEventArgs = RentSocketAsyncEventArgs(isReceive: true);
7394  if (int32TaskSocketAsyncEventArgs != null)
7395  {
7396  ConfigureBuffer(int32TaskSocketAsyncEventArgs, buffer, socketFlags, fromNetworkStream);
7397  return GetTaskForSendReceive(ReceiveAsync(int32TaskSocketAsyncEventArgs), int32TaskSocketAsyncEventArgs, fromNetworkStream, isReceive: true);
7398  }
7399  return ReceiveAsyncApm(buffer, socketFlags);
7400  }
7401 
7402  private Task<int> ReceiveAsyncApm(ArraySegment<byte> buffer, SocketFlags socketFlags)
7403  {
7404  TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>(this);
7405  BeginReceive(buffer.Array, buffer.Offset, buffer.Count, socketFlags, delegate(IAsyncResult iar)
7406  {
7407  TaskCompletionSource<int> taskCompletionSource2 = (TaskCompletionSource<int>)iar.AsyncState;
7408  try
7409  {
7410  taskCompletionSource2.TrySetResult(((Socket)taskCompletionSource2.Task.AsyncState).EndReceive(iar));
7411  }
7412  catch (Exception exception)
7413  {
7414  taskCompletionSource2.TrySetException(exception);
7415  }
7416  }, taskCompletionSource);
7417  return taskCompletionSource.Task;
7418  }
7419 
7420  internal Task<int> ReceiveAsync(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
7421  {
7422  ValidateBuffersList(buffers);
7423  Int32TaskSocketAsyncEventArgs int32TaskSocketAsyncEventArgs = RentSocketAsyncEventArgs(isReceive: true);
7424  if (int32TaskSocketAsyncEventArgs != null)
7425  {
7426  ConfigureBufferList(int32TaskSocketAsyncEventArgs, buffers, socketFlags);
7427  return GetTaskForSendReceive(ReceiveAsync(int32TaskSocketAsyncEventArgs), int32TaskSocketAsyncEventArgs, fromNetworkStream: false, isReceive: true);
7428  }
7429  return ReceiveAsyncApm(buffers, socketFlags);
7430  }
7431 
7432  private Task<int> ReceiveAsyncApm(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
7433  {
7434  TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>(this);
7435  BeginReceive(buffers, socketFlags, delegate(IAsyncResult iar)
7436  {
7437  TaskCompletionSource<int> taskCompletionSource2 = (TaskCompletionSource<int>)iar.AsyncState;
7438  try
7439  {
7440  taskCompletionSource2.TrySetResult(((Socket)taskCompletionSource2.Task.AsyncState).EndReceive(iar));
7441  }
7442  catch (Exception exception)
7443  {
7444  taskCompletionSource2.TrySetException(exception);
7445  }
7446  }, taskCompletionSource);
7447  return taskCompletionSource.Task;
7448  }
7449 
7450  internal Task<SocketReceiveFromResult> ReceiveFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)
7451  {
7452  StateTaskCompletionSource<EndPoint, SocketReceiveFromResult> stateTaskCompletionSource = new StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>(this)
7453  {
7454  _field1 = remoteEndPoint
7455  };
7456  BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref stateTaskCompletionSource._field1, delegate(IAsyncResult iar)
7457  {
7458  StateTaskCompletionSource<EndPoint, SocketReceiveFromResult> stateTaskCompletionSource2 = (StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>)iar.AsyncState;
7459  try
7460  {
7461  int receivedBytes = ((Socket)stateTaskCompletionSource2.Task.AsyncState).EndReceiveFrom(iar, ref stateTaskCompletionSource2._field1);
7462  stateTaskCompletionSource2.TrySetResult(new SocketReceiveFromResult
7463  {
7464  ReceivedBytes = receivedBytes,
7465  RemoteEndPoint = stateTaskCompletionSource2._field1
7466  });
7467  }
7468  catch (Exception exception)
7469  {
7470  stateTaskCompletionSource2.TrySetException(exception);
7471  }
7472  }, stateTaskCompletionSource);
7473  return stateTaskCompletionSource.Task;
7474  }
7475 
7476  internal Task<SocketReceiveMessageFromResult> ReceiveMessageFromAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEndPoint)
7477  {
7478  StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult> stateTaskCompletionSource = new StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>(this)
7479  {
7480  _field1 = socketFlags,
7481  _field2 = remoteEndPoint
7482  };
7483  BeginReceiveMessageFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref stateTaskCompletionSource._field2, delegate(IAsyncResult iar)
7484  {
7485  StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult> stateTaskCompletionSource2 = (StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>)iar.AsyncState;
7486  try
7487  {
7488  IPPacketInformation ipPacketInformation;
7489  int receivedBytes = ((Socket)stateTaskCompletionSource2.Task.AsyncState).EndReceiveMessageFrom(iar, ref stateTaskCompletionSource2._field1, ref stateTaskCompletionSource2._field2, out ipPacketInformation);
7490  stateTaskCompletionSource2.TrySetResult(new SocketReceiveMessageFromResult
7491  {
7492  ReceivedBytes = receivedBytes,
7493  RemoteEndPoint = stateTaskCompletionSource2._field2,
7494  SocketFlags = stateTaskCompletionSource2._field1,
7495  PacketInformation = ipPacketInformation
7496  });
7497  }
7498  catch (Exception exception)
7499  {
7500  stateTaskCompletionSource2.TrySetException(exception);
7501  }
7502  }, stateTaskCompletionSource);
7503  return stateTaskCompletionSource.Task;
7504  }
7505 
7506  internal Task<int> SendAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, bool fromNetworkStream)
7507  {
7508  ValidateBuffer(buffer);
7509  Int32TaskSocketAsyncEventArgs int32TaskSocketAsyncEventArgs = RentSocketAsyncEventArgs(isReceive: false);
7510  if (int32TaskSocketAsyncEventArgs != null)
7511  {
7512  ConfigureBuffer(int32TaskSocketAsyncEventArgs, buffer, socketFlags, fromNetworkStream);
7513  return GetTaskForSendReceive(SendAsync(int32TaskSocketAsyncEventArgs), int32TaskSocketAsyncEventArgs, fromNetworkStream, isReceive: false);
7514  }
7515  return SendAsyncApm(buffer, socketFlags);
7516  }
7517 
7518  private Task<int> SendAsyncApm(ArraySegment<byte> buffer, SocketFlags socketFlags)
7519  {
7520  TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>(this);
7521  BeginSend(buffer.Array, buffer.Offset, buffer.Count, socketFlags, delegate(IAsyncResult iar)
7522  {
7523  TaskCompletionSource<int> taskCompletionSource2 = (TaskCompletionSource<int>)iar.AsyncState;
7524  try
7525  {
7526  taskCompletionSource2.TrySetResult(((Socket)taskCompletionSource2.Task.AsyncState).EndSend(iar));
7527  }
7528  catch (Exception exception)
7529  {
7530  taskCompletionSource2.TrySetException(exception);
7531  }
7532  }, taskCompletionSource);
7533  return taskCompletionSource.Task;
7534  }
7535 
7536  internal Task<int> SendAsync(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
7537  {
7538  ValidateBuffersList(buffers);
7539  Int32TaskSocketAsyncEventArgs int32TaskSocketAsyncEventArgs = RentSocketAsyncEventArgs(isReceive: false);
7540  if (int32TaskSocketAsyncEventArgs != null)
7541  {
7542  ConfigureBufferList(int32TaskSocketAsyncEventArgs, buffers, socketFlags);
7543  return GetTaskForSendReceive(SendAsync(int32TaskSocketAsyncEventArgs), int32TaskSocketAsyncEventArgs, fromNetworkStream: false, isReceive: false);
7544  }
7545  return SendAsyncApm(buffers, socketFlags);
7546  }
7547 
7548  private Task<int> SendAsyncApm(IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
7549  {
7550  TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>(this);
7551  BeginSend(buffers, socketFlags, delegate(IAsyncResult iar)
7552  {
7553  TaskCompletionSource<int> taskCompletionSource2 = (TaskCompletionSource<int>)iar.AsyncState;
7554  try
7555  {
7556  taskCompletionSource2.TrySetResult(((Socket)taskCompletionSource2.Task.AsyncState).EndSend(iar));
7557  }
7558  catch (Exception exception)
7559  {
7560  taskCompletionSource2.TrySetException(exception);
7561  }
7562  }, taskCompletionSource);
7563  return taskCompletionSource.Task;
7564  }
7565 
7566  internal Task<int> SendToAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEP)
7567  {
7568  TaskCompletionSource<int> taskCompletionSource = new TaskCompletionSource<int>(this);
7569  BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, socketFlags, remoteEP, delegate(IAsyncResult iar)
7570  {
7571  TaskCompletionSource<int> taskCompletionSource2 = (TaskCompletionSource<int>)iar.AsyncState;
7572  try
7573  {
7574  taskCompletionSource2.TrySetResult(((Socket)taskCompletionSource2.Task.AsyncState).EndSendTo(iar));
7575  }
7576  catch (Exception exception)
7577  {
7578  taskCompletionSource2.TrySetException(exception);
7579  }
7580  }, taskCompletionSource);
7581  return taskCompletionSource.Task;
7582  }
7583 
7584  private static void ValidateBuffer(ArraySegment<byte> buffer)
7585  {
7586  if (buffer.Array == null)
7587  {
7588  throw new ArgumentNullException("Array");
7589  }
7590  if (buffer.Offset < 0 || buffer.Offset > buffer.Array.Length)
7591  {
7592  throw new ArgumentOutOfRangeException("Offset");
7593  }
7594  if (buffer.Count < 0 || buffer.Count > buffer.Array.Length - buffer.Offset)
7595  {
7596  throw new ArgumentOutOfRangeException("Count");
7597  }
7598  }
7599 
7600  private static void ValidateBuffersList(IList<ArraySegment<byte>> buffers)
7601  {
7602  if (buffers == null)
7603  {
7604  throw new ArgumentNullException("buffers");
7605  }
7606  if (buffers.Count == 0)
7607  {
7608  throw new ArgumentException(string.Format("net_sockets_zerolist", "buffers"), "buffers");
7609  }
7610  }
7611 
7612  private static void ConfigureBuffer(Int32TaskSocketAsyncEventArgs saea, ArraySegment<byte> buffer, SocketFlags socketFlags, bool wrapExceptionsInIOExceptions)
7613  {
7614  if (saea.BufferList != null)
7615  {
7616  saea.BufferList = null;
7617  }
7618  saea.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
7619  saea.SocketFlags = socketFlags;
7620  saea._wrapExceptionsInIOExceptions = wrapExceptionsInIOExceptions;
7621  }
7622 
7623  private static void ConfigureBufferList(Int32TaskSocketAsyncEventArgs saea, IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
7624  {
7625  if (saea.Buffer != null)
7626  {
7627  saea.SetBuffer(null, 0, 0);
7628  }
7629  saea.BufferList = buffers;
7630  saea.SocketFlags = socketFlags;
7631  }
7632 
7633  private Task<int> GetTaskForSendReceive(bool pending, Int32TaskSocketAsyncEventArgs saea, bool fromNetworkStream, bool isReceive)
7634  {
7635  Task<int> result;
7636  if (pending)
7637  {
7638  result = saea.GetCompletionResponsibility(out bool responsibleForReturningToPool).Task;
7639  if (responsibleForReturningToPool)
7640  {
7641  ReturnSocketAsyncEventArgs(saea, isReceive);
7642  }
7643  }
7644  else
7645  {
7646  if (saea.SocketError == SocketError.Success)
7647  {
7648  int bytesTransferred = saea.BytesTransferred;
7649  if (bytesTransferred == 0 || (fromNetworkStream && !isReceive))
7650  {
7651  result = s_zeroTask;
7652  }
7653  else
7654  {
7655  Task<int> successfullyCompletedTask = saea._successfullyCompletedTask;
7656  result = ((successfullyCompletedTask != null && successfullyCompletedTask.Result == bytesTransferred) ? successfullyCompletedTask : (saea._successfullyCompletedTask = Task.FromResult(bytesTransferred)));
7657  }
7658  }
7659  else
7660  {
7661  result = Task.FromException<int>(GetException(saea.SocketError, fromNetworkStream));
7662  }
7663  ReturnSocketAsyncEventArgs(saea, isReceive);
7664  }
7665  return result;
7666  }
7667 
7668  private static void CompleteAccept(Socket s, TaskSocketAsyncEventArgs<Socket> saea)
7669  {
7670  SocketError socketError = saea.SocketError;
7671  Socket acceptSocket = saea.AcceptSocket;
7672  bool responsibleForReturningToPool;
7673  AsyncTaskMethodBuilder<Socket> completionResponsibility = saea.GetCompletionResponsibility(out responsibleForReturningToPool);
7674  if (responsibleForReturningToPool)
7675  {
7676  s.ReturnSocketAsyncEventArgs(saea);
7677  }
7678  if (socketError == SocketError.Success)
7679  {
7680  completionResponsibility.SetResult(acceptSocket);
7681  }
7682  else
7683  {
7684  completionResponsibility.SetException(GetException(socketError));
7685  }
7686  }
7687 
7688  private static void CompleteSendReceive(Socket s, Int32TaskSocketAsyncEventArgs saea, bool isReceive)
7689  {
7690  SocketError socketError = saea.SocketError;
7691  int bytesTransferred = saea.BytesTransferred;
7692  bool wrapExceptionsInIOExceptions = saea._wrapExceptionsInIOExceptions;
7693  bool responsibleForReturningToPool;
7694  AsyncTaskMethodBuilder<int> completionResponsibility = saea.GetCompletionResponsibility(out responsibleForReturningToPool);
7695  if (responsibleForReturningToPool)
7696  {
7697  s.ReturnSocketAsyncEventArgs(saea, isReceive);
7698  }
7699  if (socketError == SocketError.Success)
7700  {
7701  completionResponsibility.SetResult(bytesTransferred);
7702  }
7703  else
7704  {
7705  completionResponsibility.SetException(GetException(socketError, wrapExceptionsInIOExceptions));
7706  }
7707  }
7708 
7709  private static Exception GetException(SocketError error, bool wrapExceptionsInIOExceptions = false)
7710  {
7711  Exception ex = new SocketException((int)error);
7712  if (!wrapExceptionsInIOExceptions)
7713  {
7714  return ex;
7715  }
7716  return new IOException(string.Format("net_io_readwritefailure", ex.Message), ex);
7717  }
7718 
7719  private Int32TaskSocketAsyncEventArgs RentSocketAsyncEventArgs(bool isReceive)
7720  {
7721  CachedTaskEventArgs cachedTaskEventArgs = LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs);
7722  Int32TaskSocketAsyncEventArgs int32TaskSocketAsyncEventArgs = isReceive ? Interlocked.Exchange(ref cachedTaskEventArgs.Receive, s_rentedInt32Sentinel) : Interlocked.Exchange(ref cachedTaskEventArgs.Send, s_rentedInt32Sentinel);
7723  if (int32TaskSocketAsyncEventArgs == s_rentedInt32Sentinel)
7724  {
7725  return null;
7726  }
7727  if (int32TaskSocketAsyncEventArgs == null)
7728  {
7729  int32TaskSocketAsyncEventArgs = new Int32TaskSocketAsyncEventArgs();
7730  int32TaskSocketAsyncEventArgs.Completed += (isReceive ? ReceiveCompletedHandler : SendCompletedHandler);
7731  }
7732  return int32TaskSocketAsyncEventArgs;
7733  }
7734 
7735  private void ReturnSocketAsyncEventArgs(Int32TaskSocketAsyncEventArgs saea, bool isReceive)
7736  {
7737  saea._accessed = false;
7738  saea._builder = default(AsyncTaskMethodBuilder<int>);
7739  saea._wrapExceptionsInIOExceptions = false;
7740  if (isReceive)
7741  {
7742  Volatile.Write(ref _cachedTaskEventArgs.Receive, saea);
7743  }
7744  else
7745  {
7746  Volatile.Write(ref _cachedTaskEventArgs.Send, saea);
7747  }
7748  }
7749 
7750  private void ReturnSocketAsyncEventArgs(TaskSocketAsyncEventArgs<Socket> saea)
7751  {
7752  saea.AcceptSocket = null;
7753  saea._accessed = false;
7754  saea._builder = default(AsyncTaskMethodBuilder<Socket>);
7755  Volatile.Write(ref _cachedTaskEventArgs.Accept, saea);
7756  }
7757 
7758  private void DisposeCachedTaskSocketAsyncEventArgs()
7759  {
7760  CachedTaskEventArgs cachedTaskEventArgs = _cachedTaskEventArgs;
7761  if (cachedTaskEventArgs != null)
7762  {
7763  Interlocked.Exchange(ref cachedTaskEventArgs.Accept, s_rentedSocketSentinel)?.Dispose();
7764  Interlocked.Exchange(ref cachedTaskEventArgs.Receive, s_rentedInt32Sentinel)?.Dispose();
7765  Interlocked.Exchange(ref cachedTaskEventArgs.Send, s_rentedInt32Sentinel)?.Dispose();
7766  }
7767  }
7768  }
7769 }
static Thread CurrentThread
Gets the currently running thread.
Definition: Thread.cs:134
bool IsThreadPoolThread
Gets a value indicating whether or not a thread belongs to the managed thread pool.
Definition: Thread.cs:124
virtual EndPoint Create(SocketAddress socketAddress)
Creates an T:System.Net.EndPoint instance from a T:System.Net.SocketAddress instance.
Definition: EndPoint.cs:37
Socket EndAccept(out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
Asynchronously accepts an incoming connection attempt and creates a new T:System.Net....
Definition: Socket.cs:5349
void Close(int timeout)
Closes the T:System.Net.Sockets.Socket connection and releases all associated resources with a specif...
Definition: Socket.cs:1338
bool Connected
Gets a value that indicates whether a T:System.Net.Sockets.Socket is connected to a remote host as of...
Definition: Socket.cs:458
int ReceiveFrom(byte[] buffer, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
Receives the specified number of bytes into the data buffer, using the specified T:System....
Definition: Socket.cs:2460
The host name is a domain name system (DNS) style host name.
bool? ExclusiveAddressUse
Gets or sets a T:System.Boolean value that specifies whether the T:System.Net.Sockets....
Definition: Socket.cs:496
void Connect(string host, int port)
Establishes a connection to a remote host. The host is specified by a host name and a port number.
Definition: Socket.cs:1219
The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method th...
Describes a set of security permissions applied to code. This class cannot be inherited.
int Receive(byte[] buffer, SocketFlags socketFlags)
Receives data from a bound T:System.Net.Sockets.Socket into a receive buffer, using the specified T:S...
Definition: Socket.cs:1960
object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName)
Returns the value of a specified T:System.Net.Sockets.Socket option, represented as an object.
Definition: Socket.cs:2708
static void Write(ref bool location, bool value)
Writes the specified value to the specified field. On systems that require it, inserts a memory barri...
Definition: Volatile.cs:186
void Listen(int backlog)
Places a T:System.Net.Sockets.Socket in a listening state.
Definition: Socket.cs:1352
SocketOptionName
Defines configuration option names.
int ReceiveTimeout
Gets or sets a value that specifies the amount of time after which a synchronous Overload:System....
Definition: Socket.cs:563
EndPoint RemoteEndPoint
Gets the remote endpoint.
Definition: Socket.cs:346
Represents a handle that has been registered when calling M:System.Threading.ThreadPool....
int Port
Gets the port number of the T:System.Net.DnsEndPoint.
Definition: DnsEndPoint.cs:43
int EndSend(IAsyncResult asyncResult)
Ends a pending asynchronous send.
Definition: Socket.cs:3888
TResult Result
Gets the result value of this T:System.Threading.Tasks.Task`1.
Definition: Task.cs:57
virtual void Dispose(bool disposing)
Releases the unmanaged resources used by the T:System.Net.Sockets.Socket, and optionally disposes of ...
Definition: Socket.cs:5660
SafeWaitHandle SafeWaitHandle
Gets or sets the native operating system handle.
Definition: WaitHandle.cs:86
unsafe int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
Receives the specified number of bytes of data into the specified location of the data buffer,...
Definition: Socket.cs:2343
static void SuppressFinalize(object obj)
Requests that the common language runtime not call the finalizer for the specified object.
Definition: GC.cs:308
void SendFile(string fileName)
Sends the file fileName to a connected T:System.Net.Sockets.Socket object with the F:System....
Definition: Socket.cs:1602
NetworkAccess
Specifies network access permissions.
Definition: NetworkAccess.cs:5
IntPtr Handle
Gets the operating system handle for the T:System.Net.Sockets.Socket.
Definition: Socket.cs:391
bool ReceiveAsync(SocketAsyncEventArgs e)
Begins an asynchronous request to receive data from a connected T:System.Net.Sockets....
Definition: Socket.cs:6918
FileMode
Specifies how the operating system should open a file.
Definition: FileMode.cs:8
Represents a non-generic collection of objects that can be individually accessed by index.
Definition: IList.cs:8
IAsyncResult BeginSendFile(string fileName, AsyncCallback callback, object state)
Sends the file fileName to a connected T:System.Net.Sockets.Socket object using the F:System....
Definition: Socket.cs:2921
bool AcceptAsync(SocketAsyncEventArgs e)
Begins an asynchronous operation to accept an incoming connection attempt.
Definition: Socket.cs:6614
bool DisconnectReuseSocket
Gets or sets a value that specifies if socket can be reused after a disconnect operation.
void RemoveAt(int index)
Removes the T:System.Collections.IList item at the specified index.
IAsyncResult BeginReceive(IList< ArraySegment< byte >> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
Begins to asynchronously receive data from a connected T:System.Net.Sockets.Socket.
Definition: Socket.cs:4357
Provides a mechanism for releasing unmanaged resources.To browse the .NET Framework source code for t...
Definition: IDisposable.cs:8
void SendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
Sends the file fileName and buffers of data to a connected T:System.Net.Sockets.Socket object using ...
Definition: Socket.cs:1617
static readonly IPAddress Any
Provides an IP address that indicates that the server must listen for client activity on all network ...
Definition: IPAddress.cs:14
int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue)
Sets low-level operating modes for the T:System.Net.Sockets.Socket using numerical control codes.
Definition: Socket.cs:2505
Definition: __Canon.cs:3
bool Poll(int microSeconds, SelectMode mode)
Determines the status of the T:System.Net.Sockets.Socket.
Definition: Socket.cs:2823
int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
Receives the specified number of bytes of data into the specified location of the data buffer,...
Definition: Socket.cs:2238
The exception that is thrown when the value of an argument is outside the allowable range of values a...
static int SizeOf(object structure)
Returns the unmanaged size of an object in bytes.
Definition: Marshal.cs:159
void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
Sets the specified T:System.Net.Sockets.Socket option to the specified T:System.Boolean value.
Definition: Socket.cs:2640
IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state)
Sends data asynchronously to a specific remote host.
Definition: Socket.cs:4042
IAsyncResult BeginSend(IList< ArraySegment< byte >> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
Sends data asynchronously to a connected T:System.Net.Sockets.Socket.
Definition: Socket.cs:3791
delegate void AsyncCallback(IAsyncResult ar)
References a method to be called when a corresponding asynchronous operation completes.
int SendTo(byte[] buffer, EndPoint remoteEP)
Sends data to the specified endpoint.
Definition: Socket.cs:1929
int Count
Gets the maximum amount of data, in bytes, to send or receive in an asynchronous operation.
int Receive(byte[] buffer)
Receives data from a bound T:System.Net.Sockets.Socket into a receive buffer.
Definition: Socket.cs:1973
virtual object Peek()
Returns the object at the beginning of the T:System.Collections.Queue without removing it.
Definition: Queue.cs:451
unsafe SocketInformation DuplicateAndClose(int targetProcessId)
Duplicates the socket reference for the target process, and closes the socket for this process.
Definition: Socket.cs:2987
int Offset
Gets the position of the first element in the range delimited by the array segment,...
Definition: ArraySegment.cs:97
byte [] ProtocolInformation
Gets or sets the protocol information for a T:System.Net.Sockets.Socket.
static bool SupportsIPv6
Gets a value that indicates whether the Framework supports IPv6 for certain obsolete T:System....
Definition: Socket.cs:247
static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object state)
Queues the specified delegate to the thread pool, but does not propagate the calling stack to the wor...
Definition: ThreadPool.cs:312
AddressFamily AddressFamily
Gets the address family of the T:System.Net.Sockets.Socket.
Definition: Socket.cs:473
int Send(byte[] buffer, SocketFlags socketFlags)
Sends data to a connected T:System.Net.Sockets.Socket using the specified T:System....
Definition: Socket.cs:1453
virtual void Enqueue(object obj)
Adds an object to the end of the T:System.Collections.Queue.
Definition: Queue.cs:407
void EndConnect(IAsyncResult asyncResult)
Ends a pending asynchronous connection request.
Definition: Socket.cs:3423
bool? NoDelay
Gets or sets a T:System.Boolean value that specifies whether the stream T:System.Net....
Definition: Socket.cs:629
unsafe int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
Sends the specified number of bytes of data to the specified endpoint, starting at the specified loca...
Definition: Socket.cs:1814
Implements the Berkeley sockets interface.
Definition: Socket.cs:16
SocketType SocketType
Gets the type of the T:System.Net.Sockets.Socket.
Definition: Socket.cs:477
short Ttl
Gets or sets a value that specifies the Time To Live (TTL) value of Internet Protocol (IP) packets se...
Definition: Socket.cs:651
int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags)
Receives the specified number of bytes from a bound T:System.Net.Sockets.Socket into the specified of...
Definition: Socket.cs:1995
IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
Begins an asynchronous request for a remote host connection. The host is specified by an T:System....
Definition: Socket.cs:3228
unsafe override string ToString()
Converts an Internet address to its standard notation.
Definition: IPAddress.cs:503
void Clear()
Removes all items from the T:System.Collections.IList.
byte [] GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength)
Returns the value of the specified T:System.Net.Sockets.Socket option in an array.
Definition: Socket.cs:2775
int IOControl(IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue)
Sets low-level operating modes for the T:System.Net.Sockets.Socket using the T:System....
Definition: Socket.cs:2539
IAsyncResult BeginAccept(int receiveSize, AsyncCallback callback, object state)
Begins an asynchronous operation to accept an incoming connection attempt and receives the first bloc...
Definition: Socket.cs:5162
static NumberFormatInfo CurrentInfo
Gets a read-only T:System.Globalization.NumberFormatInfo that formats values based on the current cul...
Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
Initializes a new instance of the T:System.Net.Sockets.Socket class using the specified address famil...
Definition: Socket.cs:884
Return information about received packets.
IAsyncResult BeginConnect(string host, int port, AsyncCallback requestCallback, object state)
Begins an asynchronous request for a remote host connection. The host is specified by a host name and...
Definition: Socket.cs:3172
The exception that is thrown when a socket error occurs.
AddressFamily AddressFamily
Gets the address family of the IP address.
Definition: IPAddress.cs:111
EndPoint RemoteEndPoint
Gets or sets the remote IP endpoint for an asynchronous operation.
static int Exchange(ref int location1, int value)
Sets a 32-bit signed integer to a specified value and returns the original value, as an atomic operat...
Represents a wrapper class for operating system handles. This class must be inherited.
Definition: SafeHandle.cs:12
void Close()
Closes the T:System.Net.Sockets.Socket connection and releases all associated resources.
Definition: Socket.cs:1323
void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue)
Sets the specified T:System.Net.Sockets.Socket option to the specified value, represented as an objec...
Definition: Socket.cs:2653
static IPAddress [] GetHostAddresses(string hostNameOrAddress)
Returns the Internet Protocol (IP) addresses for the specified host.
Definition: Dns.cs:606
The exception that is thrown when an operation is performed on a disposed object.
override AddressFamily AddressFamily
Gets the Internet Protocol (IP) address family.
Definition: DnsEndPoint.cs:31
bool? EnableBroadcast
Gets or sets a T:System.Boolean value that specifies whether the T:System.Net.Sockets....
Definition: Socket.cs:764
Provides an Internet Protocol (IP) address.
Definition: IPAddress.cs:10
IOControlCode
Specifies the IO control codes supported by the M:System.Net.Sockets.Socket.IOControl(System....
Definition: IOControlCode.cs:4
SecurityAction
Specifies the security actions that can be performed using declarative security.
IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
Begins to asynchronously receive data from a specified network device.
Definition: Socket.cs:4733
int SendTimeout
Gets or sets a value that specifies the amount of time after which a synchronous Overload:System....
Definition: Socket.cs:588
Represents the status of an asynchronous operation.
Definition: IAsyncResult.cs:9
bool TrySetResult(TResult result)
Attempts to transition the underlying T:System.Threading.Tasks.Task`1 into the F:System....
LingerOption LingerState
Gets or sets a value that specifies whether the T:System.Net.Sockets.Socket will delay closing a sock...
Definition: Socket.cs:612
SocketType
Specifies the type of socket that an instance of the T:System.Net.Sockets.Socket class represents.
Definition: SocketType.cs:4
Linger on close if unsent data is present.
bool SendPacketsAsync(SocketAsyncEventArgs e)
Sends a collection of files or in memory data buffers asynchronously to a connected T:System....
Definition: Socket.cs:7154
bool TrySetException(Exception exception)
Attempts to transition the underlying T:System.Threading.Tasks.Task`1 into the F:System....
bool SendAsync(SocketAsyncEventArgs e)
Sends data asynchronously to a connected T:System.Net.Sockets.Socket object.
Definition: Socket.cs:7101
int EndReceive(IAsyncResult asyncResult, out SocketError errorCode)
Ends a pending asynchronous read.
Definition: Socket.cs:4455
Contains option values for joining an IPv6 multicast group.
Socket(SocketType socketType, ProtocolType protocolType)
Initializes a new instance of the T:System.Net.Sockets.Socket class using the specified socket type a...
Definition: Socket.cs:873
bool?? MulticastLoopback
Gets or sets a value that specifies whether outgoing multicast packets are delivered to the sending a...
Definition: Socket.cs:721
IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
Begins to asynchronously receive data from a connected T:System.Net.Sockets.Socket.
Definition: Socket.cs:4233
Socket EndAccept(IAsyncResult asyncResult)
Asynchronously accepts an incoming connection attempt and creates a new T:System.Net....
Definition: Socket.cs:5257
SocketShutdown
Defines constants that are used by the M:System.Net.Sockets.Socket.Shutdown(System....
SelectMode
Defines the polling modes for the M:System.Net.Sockets.Socket.Poll(System.Int32,System....
Definition: SelectMode.cs:4
Provides lazy initialization routines.
IAsyncResult BeginAccept(AsyncCallback callback, object state)
Begins an asynchronous operation to accept an incoming connection attempt.
Definition: Socket.cs:4924
static readonly IPAddress IPv6Any
The M:System.Net.Sockets.Socket.Bind(System.Net.EndPoint) method uses the F:System....
Definition: IPAddress.cs:37
Represents a network endpoint as a host name or a string representation of an IP address and a port n...
Definition: DnsEndPoint.cs:7
void EndSendFile(IAsyncResult asyncResult)
Ends a pending asynchronous send of a file.
Definition: Socket.cs:3974
static void CancelConnectAsync(SocketAsyncEventArgs e)
Cancels an asynchronous request for a remote host connection.
Definition: Socket.cs:6850
virtual int Count
Gets the number of elements contained in the T:System.Collections.Queue.
Definition: Queue.cs:250
AddressFamily
Specifies the addressing scheme that an instance of the T:System.Net.Sockets.Socket class can use.
Definition: AddressFamily.cs:5
static int CompareExchange(ref int location1, int value, int comparand)
Compares two 32-bit signed integers for equality and, if they are equal, replaces the first value.
int SendTo(byte[] buffer, SocketFlags socketFlags, EndPoint remoteEP)
Sends data to a specific endpoint using the specified T:System.Net.Sockets.SocketFlags.
Definition: Socket.cs:1915
void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
Sets the specified T:System.Net.Sockets.Socket option to the specified value, represented as a byte a...
Definition: Socket.cs:2614
static bool SupportsIPv4
Gets a value indicating whether IPv4 support is available and enabled on the current host.
Definition: Socket.cs:222
Provides a T:System.IO.Stream for a file, supporting both synchronous and asynchronous read and write...
Definition: FileStream.cs:15
int ReceiveBufferSize
Gets or sets a value that specifies the size of the receive buffer of the T:System....
Definition: Socket.cs:521
IPAddress Address
Gets or sets the IP address of the endpoint.
Definition: IPEndPoint.cs:45
int Port
Gets or sets the port number of the endpoint.
Definition: IPEndPoint.cs:63
override bool Equals(object comparand)
Determines whether the specified Object is equal to the current Object.
static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count)
Copies a specified number of bytes from a source array starting at a particular offset to a destinati...
static Task FromException(Exception exception)
Creates a T:System.Threading.Tasks.Task that has completed with a specified exception.
Definition: Task.cs:4130
The exception that is thrown when an I/O error occurs.
Definition: IOException.cs:10
bool SendToAsync(SocketAsyncEventArgs e)
Sends data asynchronously to a specific remote host.
Definition: Socket.cs:7215
SocketOptionLevel
Defines socket option levels for the M:System.Net.Sockets.Socket.SetSocketOption(System....
IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state)
Begins an asynchronous request to disconnect from a remote endpoint.
Definition: Socket.cs:3327
An unspecified T:System.Net.Sockets.Socket error has occurred.
int Send(IList< ArraySegment< byte >> buffers, SocketFlags socketFlags)
Sends the set of buffers in the list to a connected T:System.Net.Sockets.Socket, using the specified ...
Definition: Socket.cs:1494
void Bind(EndPoint localEP)
Associates a T:System.Net.Sockets.Socket with a local endpoint.
Definition: Socket.cs:1038
static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
Begins an asynchronous request for a connection to a remote host.
Definition: Socket.cs:6798
Defines the underlying structure of all code access permissions.
A platform-specific type that is used to represent a pointer or a handle.
Definition: IntPtr.cs:14
Notifies one or more waiting threads that an event has occurred. This class cannot be inherited.
Represents the producer side of a T:System.Threading.Tasks.Task`1 unbound to a delegate,...
delegate void WaitOrTimerCallback(object state, bool timedOut)
Represents a method to be called when a T:System.Threading.WaitHandle is signaled or times out.
Stores serialized information from T:System.Net.EndPoint derived classes.
Definition: SocketAddress.cs:9
int Send(IList< ArraySegment< byte >> buffers, SocketFlags socketFlags, out SocketError errorCode)
Sends the set of buffers in the list to a connected T:System.Net.Sockets.Socket, using the specified ...
Definition: Socket.cs:1516
Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the ba...
Definition: Array.cs:17
Represents a network endpoint as an IP address and a port number.
Definition: IPEndPoint.cs:9
unsafe int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
Sends the specified number of bytes of data to a connected T:System.Net.Sockets.Socket,...
Definition: Socket.cs:1729
static GCHandle Alloc(object value)
Allocates a F:System.Runtime.InteropServices.GCHandleType.Normal handle for the specified object.
Definition: GCHandle.cs:98
int Send(IList< ArraySegment< byte >> buffers)
Sends the set of buffers in the list to a connected T:System.Net.Sockets.Socket.
Definition: Socket.cs:1479
Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks,...
Definition: Marshal.cs:15
Contains methods for performing volatile memory operations.
Definition: Volatile.cs:8
Represents a first-in, first-out collection of objects.
Definition: Queue.cs:13
GCHandleType
Represents the types of handles the T:System.Runtime.InteropServices.GCHandle class can allocate.
Definition: GCHandleType.cs:7
static RegisteredWaitHandle UnsafeRegisterWaitForSingleObject(WaitHandle waitObject, WaitOrTimerCallback callBack, object state, uint millisecondsTimeOutInterval, bool executeOnlyOnce)
Registers a delegate to wait for a T:System.Threading.WaitHandle, specifying a 32-bit unsigned intege...
Definition: ThreadPool.cs:100
unsafe int Receive(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode)
Receives data from a bound T:System.Net.Sockets.Socket into a receive buffer, using the specified T:S...
Definition: Socket.cs:2024
Socket EndAccept(out byte[] buffer, IAsyncResult asyncResult)
Asynchronously accepts an incoming connection attempt and creates a new T:System.Net....
Definition: Socket.cs:5325
bool? DontFragment
Gets or sets a T:System.Boolean value that specifies whether the T:System.Net.Sockets....
Definition: Socket.cs:691
Provides a way to access a managed object from unmanaged memory.
Definition: GCHandle.cs:10
A receive has completed because a close message was received.
IAsyncResult BeginReceive(IList< ArraySegment< byte >> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
Begins to asynchronously receive data from a connected T:System.Net.Sockets.Socket.
Definition: Socket.cs:4333
virtual SocketAddress Serialize()
Serializes endpoint information into a T:System.Net.SocketAddress instance.
Definition: EndPoint.cs:27
T [] Array
Gets the original array containing the range of elements that the array segment delimits.
Definition: ArraySegment.cs:85
int SendTo(byte[] buffer, int size, SocketFlags socketFlags, EndPoint remoteEP)
Sends the specified number of bytes of data to the specified endpoint using the specified T:System....
Definition: Socket.cs:1900
bool CompletedSynchronously
Gets a value that indicates whether the asynchronous operation completed synchronously.
Definition: IAsyncResult.cs:44
int EndSendTo(IAsyncResult asyncResult)
Ends a pending asynchronous send to a specific location.
Definition: Socket.cs:4132
Task< TResult > Task
Gets the T:System.Threading.Tasks.Task`1 created by this T:System.Threading.Tasks....
IAsyncResult BeginSend(IList< ArraySegment< byte >> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
Sends data asynchronously to a connected T:System.Net.Sockets.Socket.
Definition: Socket.cs:3816
void Connect(IPAddress[] addresses, int port)
Establishes a connection to a remote host. The host is specified by an array of IP addresses and a po...
Definition: Socket.cs:1260
virtual void Close()
Releases all resources held by the current T:System.Threading.WaitHandle.
Definition: WaitHandle.cs:714
int EndSend(IAsyncResult asyncResult, out SocketError errorCode)
Ends a pending asynchronous send.
Definition: Socket.cs:3911
int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint)
Ends a pending asynchronous read from a specific endpoint.
Definition: Socket.cs:4842
static void RevertAssert()
Causes any previous M:System.Security.CodeAccessPermission.Assert for the current frame to be removed...
Controls the system garbage collector, a service that automatically reclaims unused memory.
Definition: GC.cs:11
int Receive(IList< ArraySegment< byte >> buffers, SocketFlags socketFlags)
Receives data from a bound T:System.Net.Sockets.Socket into the list of receive buffers,...
Definition: Socket.cs:2114
Exception()
Initializes a new instance of the T:System.Exception class.
Definition: Exception.cs:286
Controls rights to make or accept connections on a transport address.
T:System.Net.Sockets.Socket options apply to all sockets.
The exception that is thrown when one of the arguments provided to a method is not valid.
void Demand()
Forces a T:System.Security.SecurityException at run time if all callers higher in the call stack have...
void Free()
Releases a T:System.Runtime.InteropServices.GCHandle.
Definition: GCHandle.cs:119
SocketFlags
Specifies socket send and receive behaviors.
Definition: SocketFlags.cs:5
TransmitFileOptions
The T:System.Net.Sockets.TransmitFileOptions enumeration defines values used in file transfer request...
int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
Ends a pending asynchronous read from a specific endpoint. This method also reveals more information ...
Definition: Socket.cs:4639
Encapsulates the information that is necessary to duplicate a T:System.Net.Sockets....
virtual AddressFamily AddressFamily
Gets the address family to which the endpoint belongs.
Definition: EndPoint.cs:15
int Count
Gets the number of elements in the range delimited by the array segment.
TransportType
Defines transport types for the T:System.Net.SocketPermission and T:System.Net.Sockets....
Definition: TransportType.cs:4
static void Copy(Array sourceArray, Array destinationArray, int length)
Copies a range of elements from an T:System.Array starting at the first element and pastes them into ...
Definition: Array.cs:1275
Specifies whether a T:System.Net.Sockets.Socket will remain connected after a call to the M:System....
Definition: LingerOption.cs:4
int Available
Gets the amount of data that has been received from the network and is available to be read.
Definition: Socket.cs:281
int Send(byte[] buffer)
Sends data to a connected T:System.Net.Sockets.Socket.
Definition: Socket.cs:1465
IAsyncResult BeginSendFile(string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
Sends a file and buffers of data asynchronously to a connected T:System.Net.Sockets....
Definition: Socket.cs:3704
static bool BindHandle(IntPtr osHandle)
Binds an operating system handle to the T:System.Threading.ThreadPool.
Definition: ThreadPool.cs:551
int Receive(byte[] buffer, int size, SocketFlags socketFlags)
Receives the specified number of bytes of data from a bound T:System.Net.Sockets.Socket into a receiv...
Definition: Socket.cs:1946
void Shutdown(SocketShutdown how)
Disables sends and receives on a T:System.Net.Sockets.Socket.
Definition: Socket.cs:5402
static void PtrToStructure(IntPtr ptr, object structure)
Marshals data from an unmanaged block of memory to a managed object.
Definition: Marshal.cs:1198
bool ConnectAsync(SocketAsyncEventArgs e)
Begins an asynchronous request for a connection to a remote host.
Definition: Socket.cs:6688
int Send(byte[] buffer, int size, SocketFlags socketFlags)
Sends the specified number of bytes of data to a connected T:System.Net.Sockets.Socket,...
Definition: Socket.cs:1440
virtual SafeFileHandle SafeFileHandle
Gets a T:Microsoft.Win32.SafeHandles.SafeFileHandle object that represents the operating system file ...
Definition: FileStream.cs:249
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
Definition: Exception.cs:22
IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
Begins an asynchronous request for a remote host connection.
Definition: Socket.cs:2938
Contains T:System.Net.IPAddress values used to join and drop multicast groups.
FileAccess
Defines constants for read, write, or read/write access to a file.
Definition: FileAccess.cs:9
int ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP)
Receives a datagram into the data buffer, using the specified T:System.Net.Sockets....
Definition: Socket.cs:2476
int LingerTime
Gets or sets the amount of time to remain connected after calling the M:System.Net....
Definition: LingerOption.cs:28
static readonly IntPtr Zero
A read-only field that represents a pointer or handle that has been initialized to zero.
Definition: IntPtr.cs:20
bool Blocking
Gets or sets a value that indicates whether the T:System.Net.Sockets.Socket is in blocking mode.
Definition: Socket.cs:407
IPProtectionLevel
A value that enables restriction of an IPv6 socket to a specified scope, such as addresses with the s...
EndPoint LocalEndPoint
Gets the local endpoint.
Definition: Socket.cs:309
void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
Returns the specified T:System.Net.Sockets.Socket option setting, represented as a byte array.
Definition: Socket.cs:2748
void Connect(IPAddress address, int port)
Establishes a connection to a remote host. The host is specified by an IP address and a port number.
Definition: Socket.cs:1179
override int ErrorCode
Gets the error code that is associated with this exception.
The exception that is thrown when a method call is invalid for the object's current state.
Manipulates arrays of primitive types.
Definition: Buffer.cs:11
void SetIPProtectionLevel(IPProtectionLevel level)
Set the IP protection level on a socket.
Definition: Socket.cs:2573
Provides simple domain name resolution functionality.
Definition: Dns.cs:13
Represents an asynchronous socket operation.
static bool OSSupportsIPv6
Indicates whether the underlying operating system and network adaptors support Internet Protocol vers...
Definition: Socket.cs:268
int Receive(IList< ArraySegment< byte >> buffers, SocketFlags socketFlags, out SocketError errorCode)
Receives data from a bound T:System.Net.Sockets.Socket into the list of receive buffers,...
Definition: Socket.cs:2135
int EndReceive(IAsyncResult asyncResult)
Ends a pending asynchronous read.
Definition: Socket.cs:4432
IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
Begins to asynchronously receive the specified number of bytes of data into the specified location of...
Definition: Socket.cs:4527
void Connect(EndPoint remoteEP)
Establishes a connection to a remote host.
Definition: Socket.cs:1129
int ReceiveFrom(byte[] buffer, ref EndPoint remoteEP)
Receives a datagram into the data buffer and stores the endpoint.
Definition: Socket.cs:2491
bool ReceiveFromAsync(SocketAsyncEventArgs e)
Begins to asynchronously receive data from a specified network device.
Definition: Socket.cs:6972
int Count
Gets the number of elements contained in the T:System.Collections.ICollection.
Definition: ICollection.cs:14
IAsyncResult BeginAccept(Socket acceptSocket, int receiveSize, AsyncCallback callback, object state)
Begins an asynchronous operation to accept an incoming connection attempt from a specified socket and...
Definition: Socket.cs:5180
The exception that is thrown when an invoked method is not supported, or when there is an attempt to ...
bool UseOnlyOverlappedIO
Specifies whether the socket should only use Overlapped I/O mode.
Definition: Socket.cs:439
int Receive(IList< ArraySegment< byte >> buffers)
Receives data from a bound T:System.Net.Sockets.Socket into the list of receive buffers.
Definition: Socket.cs:2100
static int GetLastWin32Error()
Returns the error code returned by the last unmanaged function that was called using platform invoke ...
bool IsBound
Gets a value that indicates whether the T:System.Net.Sockets.Socket is bound to a specific local port...
Definition: Socket.cs:486
SecurityPermissionFlag
Specifies access flags for the security permission object.
The exception that is thrown when a call is made to the M:System.Threading.Thread....
static void Select(IList checkRead, IList checkWrite, IList checkError, int microSeconds)
Determines the status of one or more sockets.
Definition: Socket.cs:2870
void Disconnect(bool reuseSocket)
Closes the socket connection and allows reuse of the socket.
Definition: Socket.cs:3380
void EndDisconnect(IAsyncResult asyncResult)
Ends a pending asynchronous disconnect request.
Definition: Socket.cs:3511
virtual object Dequeue()
Removes and returns the object at the beginning of the T:System.Collections.Queue.
Definition: Queue.cs:434
IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
Sends data asynchronously to a connected T:System.Net.Sockets.Socket.
Definition: Socket.cs:3600
static IntPtr UnsafeAddrOfPinnedArrayElement(Array arr, int index)
Gets the address of the element at the specified index inside the specified array.
Identifies a network address. This is an abstract class.
Definition: EndPoint.cs:8
IAsyncResult BeginReceive(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
Begins to asynchronously receive data from a connected T:System.Net.Sockets.Socket.
Definition: Socket.cs:4202
unsafe Socket(SocketInformation socketInformation)
Initializes a new instance of the T:System.Net.Sockets.Socket class using the specified value returne...
Definition: Socket.cs:913
Provides atomic operations for variables that are shared by multiple threads.
Definition: Interlocked.cs:10
SocketError
Defines error codes for the T:System.Net.Sockets.Socket class.
Definition: SocketError.cs:5
void Dispose()
Releases all resources used by the current instance of the T:System.Net.Sockets.Socket class.
Definition: Socket.cs:5793
Socket AcceptSocket
Gets or sets the socket to use or the socket created for accepting a connection with an asynchronous ...
bool ReceiveMessageFromAsync(SocketAsyncEventArgs e)
Begins to asynchronously receive the specified number of bytes of data into the specified location in...
Definition: Socket.cs:7036
string Host
Gets the host name or string representation of the Internet Protocol (IP) address of the host.
Definition: DnsEndPoint.cs:19
ProtocolType ProtocolType
Gets the protocol type of the T:System.Net.Sockets.Socket.
Definition: Socket.cs:481
int Send(byte[] buffer, int offset, int size, SocketFlags socketFlags)
Sends the specified number of bytes of data to a connected T:System.Net.Sockets.Socket,...
Definition: Socket.cs:1701
Socket Accept()
Creates a new T:System.Net.Sockets.Socket for a newly created connection.
Definition: Socket.cs:1384
ProtocolType
Specifies the protocols that the T:System.Net.Sockets.Socket class supports.
Definition: ProtocolType.cs:4
int Size
Gets the underlying buffer size of the T:System.Net.SocketAddress.
void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
Sets the specified T:System.Net.Sockets.Socket option to the specified integer value.
Definition: Socket.cs:2598
IAsyncResult BeginConnect(IPAddress[] addresses, int port, AsyncCallback requestCallback, object state)
Begins an asynchronous request for a remote host connection. The host is specified by an T:System....
Definition: Socket.cs:3273
bool Reset()
Sets the state of the event to nonsignaled, causing threads to block.
Presents the packet information from a call to M:System.Net.Sockets.Socket.ReceiveMessageFrom(System....
Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I...
Definition: ThreadPool.cs:14
FileShare
Contains constants for controlling the kind of access other T:System.IO.FileStream objects can have t...
Definition: FileShare.cs:9
Represents an asynchronous operation that can return a value.
Definition: Task.cs:18
IAsyncResult BeginSend(byte[] buffer, int offset, int size, SocketFlags socketFlags, AsyncCallback callback, object state)
Sends data asynchronously to a connected T:System.Net.Sockets.Socket.
Definition: Socket.cs:3570
bool Unregister(WaitHandle waitObject)
Cancels a registered wait operation issued by the M:System.Threading.ThreadPool.RegisterWaitForSingle...
bool? DualMode
Gets or sets a T:System.Boolean value that specifies whether the T:System.Net.Sockets....
Definition: Socket.cs:783
int SendBufferSize
Gets or sets a value that specifies the size of the send buffer of the T:System.Net....
Definition: Socket.cs:542
bool DisconnectAsync(SocketAsyncEventArgs e)
Begins an asynchronous request to disconnect from a remote endpoint.
Definition: Socket.cs:6867
static void SpinWait(int iterations)
Causes a thread to wait the number of times defined by the iterations parameter.
Definition: Thread.cs:779
Provides culture-specific information for formatting and parsing numeric values.
static bool OSSupportsIPv4
Indicates whether the underlying operating system and network adaptors support Internet Protocol vers...
Definition: Socket.cs:234
Creates and controls a thread, sets its priority, and gets its status.
Definition: Thread.cs:18