18 private class CacheSet
20 internal CallbackClosure ConnectClosureCache;
22 internal CallbackClosure AcceptClosureCache;
24 internal CallbackClosure SendClosureCache;
26 internal CallbackClosure ReceiveClosureCache;
28 internal OverlappedCache SendOverlappedCache;
30 internal OverlappedCache ReceiveOverlappedCache;
33 private class MultipleAddressConnectAsyncResult : ContextAwareResult
49 if (addresses !=
null && index > 0 && index < addresses.Length)
58 : base(socket, myState, myCallBack)
60 this.addresses = addresses;
68 internal TField1 _field1;
70 public StateTaskCompletionSource(
object baseState)
76 private class StateTaskCompletionSource<TField1, TField2, TResult> : StateTaskCompletionSource<TField1, TResult>
78 internal TField2 _field2;
80 public StateTaskCompletionSource(
object baseState)
86 private sealed
class CachedTaskEventArgs
88 public TaskSocketAsyncEventArgs<Socket>
Accept;
90 public Int32TaskSocketAsyncEventArgs
Receive;
92 public Int32TaskSocketAsyncEventArgs
Send;
99 internal bool _accessed;
105 responsibleForReturningToPool = _accessed;
113 private sealed
class Int32TaskSocketAsyncEventArgs : TaskSocketAsyncEventArgs<int>
115 internal Task<int> _successfullyCompletedTask;
117 internal bool _wrapExceptionsInIOExceptions;
120 internal const int DefaultCloseTimeout = -1;
122 private object m_AcceptQueueOrConnectResult;
124 private SafeCloseSocket m_Handle;
130 private bool m_IsConnected;
132 private bool m_IsDisconnected;
134 private bool willBlock =
true;
136 private bool willBlockInternal =
true;
138 private bool isListening;
140 private bool m_NonBlockingConnectInProgress;
142 private EndPoint m_NonBlockingConnectRightEndPoint;
150 private CacheSet m_Caches;
152 internal static volatile bool UseOverlappedIO;
154 private bool useOverlappedIO;
156 private bool m_BoundToThreadPool;
158 private bool m_ReceivingPacketInformation;
164 private AsyncEventBits m_BlockEventBits;
168 private DynamicWinsockMethods m_DynamicWinsockMethods;
170 private static object s_InternalSyncObject;
172 private int m_CloseTimeout = -1;
174 private int m_IntCleanedUp;
176 private const int microcnv = 1000000;
178 private static readonly
int protocolInformationSize =
Marshal.
SizeOf(typeof(UnsafeNclNativeMethods.OSSOCK.WSAPROTOCOL_INFO));
180 internal static volatile bool s_SupportsIPv4;
182 internal static volatile bool s_SupportsIPv6;
184 internal static volatile bool s_OSSupportsIPv6;
186 internal static volatile bool s_Initialized;
190 private static volatile bool s_LoggingEnabled;
192 internal static volatile bool s_PerfCountersEnabled;
194 private static readonly EventHandler<SocketAsyncEventArgs> AcceptCompletedHandler = delegate(
object s,
SocketAsyncEventArgs e)
196 CompleteAccept((
Socket)s, (TaskSocketAsyncEventArgs<Socket>)e);
199 private static readonly EventHandler<SocketAsyncEventArgs> ReceiveCompletedHandler = delegate(
object s,
SocketAsyncEventArgs e)
201 CompleteSendReceive((
Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive:
true);
204 private static readonly EventHandler<SocketAsyncEventArgs> SendCompletedHandler = delegate(
object s,
SocketAsyncEventArgs e)
206 CompleteSendReceive((
Socket)s, (Int32TaskSocketAsyncEventArgs)e, isReceive:
false);
209 private static readonly TaskSocketAsyncEventArgs<Socket> s_rentedSocketSentinel =
new TaskSocketAsyncEventArgs<Socket>();
211 private static readonly Int32TaskSocketAsyncEventArgs s_rentedInt32Sentinel =
new Int32TaskSocketAsyncEventArgs();
213 private static readonly
Task<int> s_zeroTask =
Task.FromResult(0);
215 private CachedTaskEventArgs _cachedTaskEventArgs;
220 [Obsolete(
"SupportsIPv4 is obsoleted for this type, please use OSSupportsIPv4 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
226 return s_SupportsIPv4;
238 return s_SupportsIPv4;
245 [Obsolete(
"SupportsIPv6 is obsoleted for this type, please use OSSupportsIPv6 instead. http://go.microsoft.com/fwlink/?linkid=14202")]
251 return s_SupportsIPv6;
255 internal static bool LegacySupportsIPv6
260 return s_SupportsIPv6;
272 return s_OSSupportsIPv6;
289 SocketError socketError = UnsafeNclNativeMethods.OSSOCK.ioctlsocket(m_Handle, 1074030207, ref argp);
293 UpdateStatusAfterSocketError(ex);
294 if (s_LoggingEnabled)
296 Logging.Exception(Logging.Sockets,
this,
"Available", ex);
316 if (m_NonBlockingConnectInProgress &&
Poll(0,
SelectMode.SelectWrite))
318 m_IsConnected =
true;
319 m_RightEndPoint = m_NonBlockingConnectRightEndPoint;
320 m_NonBlockingConnectInProgress =
false;
322 if (m_RightEndPoint ==
null)
327 if (UnsafeNclNativeMethods.OSSOCK.getsockname(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size) != 0)
330 UpdateStatusAfterSocketError(ex);
331 if (s_LoggingEnabled)
333 Logging.Exception(Logging.Sockets,
this,
"LocalEndPoint", ex);
337 return m_RightEndPoint.
Create(socketAddress);
353 if (m_RemoteEndPoint ==
null)
355 if (m_NonBlockingConnectInProgress &&
Poll(0,
SelectMode.SelectWrite))
357 m_IsConnected =
true;
358 m_RightEndPoint = m_NonBlockingConnectRightEndPoint;
359 m_NonBlockingConnectInProgress =
false;
361 if (m_RightEndPoint ==
null)
366 if (UnsafeNclNativeMethods.OSSOCK.getpeername(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size) != 0)
369 UpdateStatusAfterSocketError(ex);
370 if (s_LoggingEnabled)
372 Logging.Exception(Logging.Sockets,
this,
"RemoteEndPoint", ex);
378 m_RemoteEndPoint = m_RightEndPoint.
Create(socketAddress);
384 return m_RemoteEndPoint;
394 ExceptionHelper.UnmanagedPermission.Demand();
395 return m_Handle.DangerousGetHandle();
399 internal SafeCloseSocket
SafeHandle => m_Handle;
419 SocketError socketError = InternalSetBlocking(value, out current);
420 if (socketError != 0)
423 UpdateStatusAfterSocketError(ex);
424 if (s_LoggingEnabled)
426 Logging.Exception(Logging.Sockets,
this,
"Blocking", ex);
442 return useOverlappedIO;
446 if (m_BoundToThreadPool)
450 useOverlappedIO = value;
461 if (m_NonBlockingConnectInProgress &&
Poll(0,
SelectMode.SelectWrite))
463 m_IsConnected =
true;
464 m_RightEndPoint = m_NonBlockingConnectRightEndPoint;
465 m_NonBlockingConnectInProgress =
false;
467 return m_IsConnected;
486 public bool IsBound => m_RightEndPoint !=
null;
666 if (value < 0 || value > 255)
802 private bool IsDualMode
814 private bool CanUseAcceptEx
820 return m_IsDisconnected;
826 private static object InternalSyncObject
830 if (s_InternalSyncObject ==
null)
832 object value =
new object();
835 return s_InternalSyncObject;
839 private CacheSet Caches
843 if (m_Caches ==
null)
845 m_Caches =
new CacheSet();
851 internal bool CleanedUp => m_IntCleanedUp == 1;
886 s_LoggingEnabled = Logging.On;
887 if (s_LoggingEnabled)
889 Logging.Enter(Logging.Sockets,
this,
"Socket", addressFamily);
892 m_Handle = SafeCloseSocket.CreateWSASocket(addressFamily, socketType, protocolType);
893 if (m_Handle.IsInvalid)
897 this.addressFamily = addressFamily;
898 this.socketType = socketType;
899 this.protocolType = protocolType;
900 IPProtectionLevel iPProtectionLevel = SettingsSectionInternal.Section.IPProtectionLevel;
905 if (s_LoggingEnabled)
907 Logging.Exit(Logging.Sockets,
this,
"Socket",
null);
915 s_LoggingEnabled = Logging.On;
916 if (s_LoggingEnabled)
918 Logging.Enter(Logging.Sockets,
this,
"Socket", addressFamily);
920 ExceptionHelper.UnrestrictedSocketPermission.Demand();
924 throw new ArgumentException(SR.GetString(
"net_sockets_invalid_socketinformation"),
"socketInformation.ProtocolInformation");
927 fixed (
byte* ptr = protocolInformation)
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;
935 if (m_Handle.IsInvalid)
940 throw new ArgumentException(SR.GetString(
"net_sockets_invalid_socketinformation"),
"socketInformation");
948 m_IsConnected = socketInformation.IsConnected;
949 willBlock = !socketInformation.IsNonBlocking;
950 InternalSetBlocking(willBlock);
951 isListening = socketInformation.IsListening;
953 if (socketInformation.RemoteEndPoint !=
null)
955 m_RightEndPoint = socketInformation.RemoteEndPoint;
956 m_RemoteEndPoint = socketInformation.RemoteEndPoint;
973 socketError = UnsafeNclNativeMethods.OSSOCK.getsockname(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size);
983 m_RightEndPoint = endPoint.
Create(socketAddress);
990 if (s_LoggingEnabled)
992 Logging.Exit(Logging.Sockets,
this,
"Socket",
null);
996 private Socket(SafeCloseSocket fd)
998 s_LoggingEnabled = Logging.On;
999 if (s_LoggingEnabled)
1001 Logging.Enter(Logging.Sockets,
this,
"Socket",
null);
1003 InitializeSockets();
1004 if (fd ==
null || fd.IsInvalid)
1012 if (s_LoggingEnabled)
1014 Logging.Exit(Logging.Sockets,
this,
"Socket",
null);
1020 if (family != addressFamily)
1040 if (s_LoggingEnabled)
1042 Logging.Enter(Logging.Sockets,
this,
"Bind", localEP);
1048 if (localEP ==
null)
1054 if (iPEndPoint !=
null)
1056 iPEndPoint = iPEndPoint.Snapshot();
1057 endPoint = RemapIPEndPoint(iPEndPoint);
1059 socketPermission.
Demand();
1063 ExceptionHelper.UnmanagedPermission.Demand();
1065 SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(endPoint);
1066 DoBind(endPoint, socketAddress);
1067 if (s_LoggingEnabled)
1069 Logging.Exit(Logging.Sockets,
this,
"Bind",
"");
1073 internal void InternalBind(
EndPoint localEP)
1075 if (s_LoggingEnabled)
1077 Logging.Enter(Logging.Sockets,
this,
"InternalBind", localEP);
1083 EndPoint remoteEP = localEP;
1084 SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP);
1085 DoBind(remoteEP, socketAddress);
1086 if (s_LoggingEnabled)
1088 Logging.Exit(Logging.Sockets,
this,
"InternalBind",
"");
1092 private void DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
1094 IPEndPoint iPEndPoint = endPointSnapshot as IPEndPoint;
1095 if (!
OSSupportsIPv4 && iPEndPoint !=
null && iPEndPoint.Address.IsIPv4MappedToIPv6)
1097 SocketException ex =
new SocketException(
SocketError.InvalidArgument);
1098 UpdateStatusAfterSocketError(ex);
1099 if (s_LoggingEnabled)
1101 Logging.Exception(Logging.Sockets,
this,
"DoBind", ex);
1105 if (UnsafeNclNativeMethods.OSSOCK.bind(m_Handle, socketAddress.m_Buffer, socketAddress.m_Size) != 0)
1107 SocketException ex2 =
new SocketException();
1108 UpdateStatusAfterSocketError(ex2);
1109 if (s_LoggingEnabled)
1111 Logging.Exception(Logging.Sockets,
this,
"DoBind", ex2);
1115 if (m_RightEndPoint ==
null)
1117 m_RightEndPoint = endPointSnapshot;
1135 if (remoteEP ==
null)
1139 if (m_IsDisconnected)
1147 ValidateBlockingMode();
1149 if (dnsEndPoint !=
null)
1159 SocketAddress socketAddress = CheckCacheRemote(ref remoteEP2, isOverwrite:
true);
1162 m_NonBlockingConnectRightEndPoint = remoteEP2;
1163 m_NonBlockingConnectInProgress =
true;
1165 DoConnect(remoteEP2, socketAddress);
1181 if (s_LoggingEnabled)
1183 Logging.Enter(Logging.Sockets,
this,
"Connect", address);
1189 if (address ==
null)
1193 if (!ValidationHelper.ValidateTcpPort(port))
1203 if (s_LoggingEnabled)
1205 Logging.Exit(Logging.Sockets,
this,
"Connect",
null);
1221 if (s_LoggingEnabled)
1223 Logging.Enter(Logging.Sockets,
this,
"Connect", host);
1233 if (!ValidationHelper.ValidateTcpPort(port))
1243 if (s_LoggingEnabled)
1245 Logging.Exit(Logging.Sockets,
this,
"Connect",
null);
1262 if (s_LoggingEnabled)
1264 Logging.Enter(Logging.Sockets,
this,
"Connect", addresses);
1270 if (addresses ==
null)
1274 if (addresses.Length == 0)
1276 throw new ArgumentException(SR.GetString(
"net_sockets_invalid_ipaddress_length"),
"addresses");
1278 if (!ValidationHelper.ValidateTcpPort(port))
1287 foreach (
IPAddress iPAddress
in addresses)
1298 if (NclUtilities.IsFatal(ex2))
1314 throw new ArgumentException(SR.GetString(
"net_invalidAddressList"),
"addresses");
1316 if (s_LoggingEnabled)
1318 Logging.Exit(Logging.Sockets,
this,
"Connect",
null);
1325 if (s_LoggingEnabled)
1327 Logging.Enter(Logging.Sockets,
this,
"Close",
null);
1330 if (s_LoggingEnabled)
1332 Logging.Exit(Logging.Sockets,
this,
"Close",
null);
1344 m_CloseTimeout = timeout;
1354 if (s_LoggingEnabled)
1356 Logging.Enter(Logging.Sockets,
this,
"Listen", backlog);
1362 if (UnsafeNclNativeMethods.OSSOCK.listen(m_Handle, backlog) != 0)
1365 UpdateStatusAfterSocketError(ex);
1366 if (s_LoggingEnabled)
1368 Logging.Exception(Logging.Sockets,
this,
"Listen", ex);
1373 if (s_LoggingEnabled)
1375 Logging.Exit(Logging.Sockets,
this,
"Listen",
"");
1386 if (s_LoggingEnabled)
1388 Logging.Enter(Logging.Sockets,
this,
"Accept",
"");
1394 if (m_RightEndPoint ==
null)
1402 if (m_IsDisconnected)
1406 ValidateBlockingMode();
1408 SafeCloseSocket safeCloseSocket = SafeCloseSocket.Accept(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size);
1409 if (safeCloseSocket.IsInvalid)
1412 UpdateStatusAfterSocketError(ex);
1413 if (s_LoggingEnabled)
1415 Logging.Exception(Logging.Sockets,
this,
"Accept", ex);
1419 Socket socket = CreateAcceptSocket(safeCloseSocket, m_RightEndPoint.
Create(socketAddress), needCancelSelect:
false);
1420 if (s_LoggingEnabled)
1423 Logging.Exit(Logging.Sockets,
this,
"Accept", socket);
1442 return Send(buffer, 0, size, socketFlags);
1455 return Send(buffer, 0, (buffer !=
null) ? buffer.Length : 0, socketFlags);
1467 return Send(buffer, 0, (buffer !=
null) ? buffer.Length : 0,
SocketFlags.None);
1497 int result =
Send(buffers, socketFlags, out errorCode);
1518 if (s_LoggingEnabled)
1520 Logging.Enter(Logging.Sockets,
this,
"Send",
"");
1526 if (buffers ==
null)
1530 if (buffers.Count == 0)
1532 throw new ArgumentException(SR.GetString(
"net_sockets_zerolist",
"buffers"),
"buffers");
1534 ValidateBlockingMode();
1536 int count = buffers.Count;
1537 WSABuffer[] array =
new WSABuffer[count];
1539 int bytesTransferred;
1543 for (
int i = 0; i < count; i++)
1546 ValidationHelper.ValidateSegment(segment);
1548 array[i].Length = segment.
Count;
1551 errorCode = UnsafeNclNativeMethods.OSSOCK.WSASend_Blocking(m_Handle.DangerousGetHandle(), array, count, out bytesTransferred, socketFlags, SafeNativeOverlapped.Zero,
IntPtr.
Zero);
1561 for (
int j = 0; j < array2.Length; j++)
1563 if (array2[j].IsAllocated)
1572 UpdateStatusAfterSocketError(errorCode);
1573 if (s_LoggingEnabled)
1575 Logging.Exception(Logging.Sockets,
this,
"Send",
new SocketException(errorCode));
1576 Logging.Exit(Logging.Sockets,
this,
"Send", 0);
1580 if (s_PerfCountersEnabled && bytesTransferred > 0)
1582 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, bytesTransferred);
1585 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
1588 if (s_LoggingEnabled)
1590 Logging.Exit(Logging.Sockets,
this,
"Send", bytesTransferred);
1592 return bytesTransferred;
1619 if (s_LoggingEnabled)
1621 Logging.Enter(Logging.Sockets,
this,
"SendFile",
"");
1631 ValidateBlockingMode();
1632 TransmitFileOverlappedAsyncResult transmitFileOverlappedAsyncResult =
new TransmitFileOverlappedAsyncResult(
this);
1634 if (fileName !=
null && fileName.Length > 0)
1639 if (fileStream !=
null)
1641 ExceptionHelper.UnmanagedPermission.Assert();
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)))
1662 transmitFileOverlappedAsyncResult.SyncReleaseUnmanagedStructures();
1664 if (socketError != 0)
1667 UpdateStatusAfterSocketError(ex);
1668 if (s_LoggingEnabled)
1670 Logging.Exception(Logging.Sockets,
this,
"SendFile", ex);
1676 SetToDisconnected();
1677 m_RemoteEndPoint =
null;
1679 if (s_LoggingEnabled)
1681 Logging.Exit(Logging.Sockets,
this,
"SendFile", socketError);
1704 int result =
Send(buffer, offset, size, socketFlags, out errorCode);
1731 if (s_LoggingEnabled)
1733 Logging.Enter(Logging.Sockets,
this,
"Send",
"");
1743 if (offset < 0 || offset > buffer.Length)
1747 if (size < 0 || size > buffer.Length - offset)
1752 ValidateBlockingMode();
1754 if (buffer.Length == 0)
1756 num = UnsafeNclNativeMethods.OSSOCK.send(m_Handle.DangerousGetHandle(),
null, 0, socketFlags);
1760 fixed (
byte* ptr = buffer)
1762 num = UnsafeNclNativeMethods.OSSOCK.send(m_Handle.DangerousGetHandle(), ptr + offset, size, socketFlags);
1768 UpdateStatusAfterSocketError(errorCode);
1769 if (s_LoggingEnabled)
1771 Logging.Exception(Logging.Sockets,
this,
"Send",
new SocketException(errorCode));
1772 Logging.Exit(Logging.Sockets,
this,
"Send", 0);
1776 if (s_PerfCountersEnabled && num > 0)
1778 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, num);
1781 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
1784 if (s_LoggingEnabled)
1786 Logging.Dump(Logging.Sockets,
this,
"Send", buffer, offset, size);
1788 if (s_LoggingEnabled)
1790 Logging.Exit(Logging.Sockets,
this,
"Send", num);
1816 if (s_LoggingEnabled)
1818 Logging.Enter(Logging.Sockets,
this,
"SendTo",
"");
1828 if (remoteEP ==
null)
1832 if (offset < 0 || offset > buffer.Length)
1836 if (size < 0 || size > buffer.Length - offset)
1840 ValidateBlockingMode();
1842 SocketAddress socketAddress = CheckCacheRemote(ref remoteEP2, isOverwrite:
false);
1844 if (buffer.Length == 0)
1846 num = UnsafeNclNativeMethods.OSSOCK.sendto(m_Handle.DangerousGetHandle(),
null, 0, socketFlags, socketAddress.m_Buffer, socketAddress.m_Size);
1850 fixed (
byte* ptr = buffer)
1852 num = UnsafeNclNativeMethods.OSSOCK.sendto(m_Handle.DangerousGetHandle(), ptr + offset, size, socketFlags, socketAddress.m_Buffer, socketAddress.m_Size);
1858 UpdateStatusAfterSocketError(ex);
1859 if (s_LoggingEnabled)
1861 Logging.Exception(Logging.Sockets,
this,
"SendTo", ex);
1865 if (m_RightEndPoint ==
null)
1867 m_RightEndPoint = remoteEP2;
1869 if (s_PerfCountersEnabled && num > 0)
1871 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, num);
1874 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
1877 if (s_LoggingEnabled)
1879 Logging.Dump(Logging.Sockets,
this,
"SendTo", buffer, offset, size);
1881 if (s_LoggingEnabled)
1883 Logging.Exit(Logging.Sockets,
this,
"SendTo", num);
1902 return SendTo(buffer, 0, size, socketFlags, remoteEP);
1917 return SendTo(buffer, 0, (buffer !=
null) ? buffer.Length : 0, socketFlags, remoteEP);
1931 return SendTo(buffer, 0, (buffer !=
null) ? buffer.Length : 0,
SocketFlags.None, remoteEP);
1948 return Receive(buffer, 0, size, socketFlags);
1962 return Receive(buffer, 0, (buffer !=
null) ? buffer.Length : 0, socketFlags);
1998 int result =
Receive(buffer, offset, size, socketFlags, out errorCode);
2026 if (s_LoggingEnabled)
2028 Logging.Enter(Logging.Sockets,
this,
"Receive",
"");
2038 if (offset < 0 || offset > buffer.Length)
2042 if (size < 0 || size > buffer.Length - offset)
2046 ValidateBlockingMode();
2049 if (buffer.Length == 0)
2051 num = UnsafeNclNativeMethods.OSSOCK.recv(m_Handle.DangerousGetHandle(),
null, 0, socketFlags);
2055 fixed (
byte* ptr = buffer)
2057 num = UnsafeNclNativeMethods.OSSOCK.recv(m_Handle.DangerousGetHandle(), ptr + offset, size, socketFlags);
2063 UpdateStatusAfterSocketError(errorCode);
2064 if (s_LoggingEnabled)
2066 Logging.Exception(Logging.Sockets,
this,
"Receive",
new SocketException(errorCode));
2067 Logging.Exit(Logging.Sockets,
this,
"Receive", 0);
2071 if (s_PerfCountersEnabled)
2074 if (num > 0 && !flag)
2076 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, num);
2079 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
2083 if (s_LoggingEnabled)
2085 Logging.Dump(Logging.Sockets,
this,
"Receive", buffer, offset, num);
2087 if (s_LoggingEnabled)
2089 Logging.Exit(Logging.Sockets,
this,
"Receive", num);
2117 int result =
Receive(buffers, socketFlags, out errorCode);
2137 if (s_LoggingEnabled)
2139 Logging.Enter(Logging.Sockets,
this,
"Receive",
"");
2145 if (buffers ==
null)
2149 if (buffers.Count == 0)
2151 throw new ArgumentException(SR.GetString(
"net_sockets_zerolist",
"buffers"),
"buffers");
2153 ValidateBlockingMode();
2154 int count = buffers.Count;
2155 WSABuffer[] array =
new WSABuffer[count];
2158 int bytesTransferred;
2162 for (
int i = 0; i < count; i++)
2165 ValidationHelper.ValidateSegment(segment);
2167 array[i].Length = segment.
Count;
2170 errorCode = UnsafeNclNativeMethods.OSSOCK.WSARecv_Blocking(m_Handle.DangerousGetHandle(), array, count, out bytesTransferred, ref socketFlags, SafeNativeOverlapped.Zero,
IntPtr.
Zero);
2180 for (
int j = 0; j < array2.Length; j++)
2182 if (array2[j].IsAllocated)
2191 UpdateStatusAfterSocketError(errorCode);
2192 if (s_LoggingEnabled)
2194 Logging.Exception(Logging.Sockets,
this,
"Receive",
new SocketException(errorCode));
2195 Logging.Exit(Logging.Sockets,
this,
"Receive", 0);
2199 if (s_PerfCountersEnabled)
2202 if (bytesTransferred > 0 && !flag)
2204 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, bytesTransferred);
2207 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
2211 if (s_LoggingEnabled)
2213 Logging.Exit(Logging.Sockets,
this,
"Receive", bytesTransferred);
2215 return bytesTransferred;
2240 if (s_LoggingEnabled)
2242 Logging.Enter(Logging.Sockets,
this,
"ReceiveMessageFrom",
"");
2252 if (remoteEP ==
null)
2256 if (!CanTryAddressFamily(remoteEP.AddressFamily))
2258 throw new ArgumentException(SR.GetString(
"net_InvalidEndPointAddressFamily", remoteEP.AddressFamily, addressFamily),
"remoteEP");
2260 if (offset < 0 || offset > buffer.Length)
2264 if (size < 0 || size > buffer.Length - offset)
2268 if (m_RightEndPoint ==
null)
2272 ValidateBlockingMode();
2274 SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP2);
2275 ReceiveMessageOverlappedAsyncResult receiveMessageOverlappedAsyncResult =
new ReceiveMessageOverlappedAsyncResult(
this,
null,
null);
2276 receiveMessageOverlappedAsyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags);
2278 int bytesTransferred = 0;
2280 SetReceivingPacketInformation();
2290 receiveMessageOverlappedAsyncResult.SyncReleaseUnmanagedStructures();
2292 if (socketError != 0 && socketError !=
SocketError.MessageSize)
2295 UpdateStatusAfterSocketError(ex);
2296 if (s_LoggingEnabled)
2298 Logging.Exception(Logging.Sockets,
this,
"ReceiveMessageFrom", ex);
2302 if (!socketAddress2.
Equals(receiveMessageOverlappedAsyncResult.m_SocketAddress))
2306 remoteEP = remoteEP2.Create(receiveMessageOverlappedAsyncResult.m_SocketAddress);
2311 if (m_RightEndPoint ==
null)
2313 m_RightEndPoint = remoteEP2;
2316 socketFlags = receiveMessageOverlappedAsyncResult.m_flags;
2317 ipPacketInformation = receiveMessageOverlappedAsyncResult.m_IPPacketInformation;
2318 if (s_LoggingEnabled)
2320 Logging.Exit(Logging.Sockets,
this,
"ReceiveMessageFrom", socketError);
2322 return bytesTransferred;
2345 if (s_LoggingEnabled)
2347 Logging.Enter(Logging.Sockets,
this,
"ReceiveFrom",
"");
2357 if (remoteEP ==
null)
2361 if (!CanTryAddressFamily(remoteEP.AddressFamily))
2363 throw new ArgumentException(SR.GetString(
"net_InvalidEndPointAddressFamily", remoteEP.AddressFamily, addressFamily),
"remoteEP");
2365 if (offset < 0 || offset > buffer.Length)
2369 if (size < 0 || size > buffer.Length - offset)
2373 if (m_RightEndPoint ==
null)
2377 ValidateBlockingMode();
2379 SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP2);
2382 if (buffer.Length == 0)
2384 num = UnsafeNclNativeMethods.OSSOCK.recvfrom(m_Handle.DangerousGetHandle(),
null, 0, socketFlags, socketAddress.m_Buffer, ref socketAddress.m_Size);
2388 fixed (
byte* ptr = buffer)
2390 num = UnsafeNclNativeMethods.OSSOCK.recvfrom(m_Handle.DangerousGetHandle(), ptr + offset, size, socketFlags, socketAddress.m_Buffer, ref socketAddress.m_Size);
2397 UpdateStatusAfterSocketError(ex);
2398 if (s_LoggingEnabled)
2400 Logging.Exception(Logging.Sockets,
this,
"ReceiveFrom", ex);
2407 if (!socketAddress2.
Equals(socketAddress))
2411 remoteEP = remoteEP2.Create(socketAddress);
2416 if (m_RightEndPoint ==
null)
2418 m_RightEndPoint = remoteEP2;
2425 if (s_PerfCountersEnabled && num > 0)
2427 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, num);
2430 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
2433 if (s_LoggingEnabled)
2435 Logging.Dump(Logging.Sockets,
this,
"ReceiveFrom", buffer, offset, size);
2437 if (s_LoggingEnabled)
2439 Logging.Exit(Logging.Sockets,
this,
"ReceiveFrom", num);
2462 return ReceiveFrom(buffer, 0, size, socketFlags, ref remoteEP);
2478 return ReceiveFrom(buffer, 0, (buffer !=
null) ? buffer.Length : 0, socketFlags, ref remoteEP);
2505 public int IOControl(
int ioControlCode,
byte[] optionInValue,
byte[] optionOutValue)
2511 if (ioControlCode == -2147195266)
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);
2521 UpdateStatusAfterSocketError(ex);
2522 if (s_LoggingEnabled)
2524 Logging.Exception(Logging.Sockets,
this,
"IOControl", ex);
2528 return bytesTransferred;
2541 return IOControl((
int)ioControlCode, optionInValue, optionOutValue);
2550 if ((
int)ioControlCode == -2147195266)
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);
2558 SocketException ex =
new SocketException();
2559 UpdateStatusAfterSocketError(ex);
2560 if (s_LoggingEnabled)
2562 Logging.Exception(Logging.Sockets,
this,
"IOControl", ex);
2566 return bytesTransferred;
2577 throw new ArgumentException(SR.GetString(
"net_sockets_invalid_optionValue_all"),
"level");
2604 CheckSetOptionPermissions(optionLevel, optionName);
2620 CheckSetOptionPermissions(optionLevel, optionName);
2621 SocketError socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(m_Handle, optionLevel, optionName, optionValue, (optionValue !=
null) ? optionValue.Length : 0);
2625 UpdateStatusAfterSocketError(ex);
2626 if (s_LoggingEnabled)
2628 Logging.Exception(Logging.Sockets,
this,
"SetSocketOption", ex);
2659 if (optionValue ==
null)
2663 CheckSetOptionPermissions(optionLevel, optionName);
2667 if (lingerOption ==
null)
2669 throw new ArgumentException(SR.GetString(
"net_sockets_invalid_optionValue",
"LingerOption"),
"optionValue");
2673 throw new ArgumentException(SR.GetString(
"ArgumentOutOfRange_Bounds_Lower_Upper", 0, 65535),
"optionValue.LingerTime");
2675 setLingerOption(lingerOption);
2680 if (multicastOption ==
null)
2682 throw new ArgumentException(SR.GetString(
"net_sockets_invalid_optionValue",
"MulticastOption"),
"optionValue");
2684 setMulticastOption(optionName, multicastOption);
2690 throw new ArgumentException(SR.GetString(
"net_sockets_invalid_optionValue_all"),
"optionValue");
2693 if (pv6MulticastOption ==
null)
2695 throw new ArgumentException(SR.GetString(
"net_sockets_invalid_optionValue",
"IPv6MulticastOption"),
"optionValue");
2697 setIPv6MulticastOption(optionName, pv6MulticastOption);
2716 return getLingerOpt();
2720 return getMulticastOpt(optionName);
2724 return getIPv6MulticastOpt(optionName);
2726 int optionValue = 0;
2727 int optionLength = 4;
2728 SocketError socketError = UnsafeNclNativeMethods.OSSOCK.getsockopt(m_Handle, optionLevel, optionName, out optionValue, ref optionLength);
2732 UpdateStatusAfterSocketError(ex);
2733 if (s_LoggingEnabled)
2735 Logging.Exception(Logging.Sockets,
this,
"GetSocketOption", ex);
2754 int optionLength = (optionValue !=
null) ? optionValue.Length : 0;
2755 SocketError socketError = UnsafeNclNativeMethods.OSSOCK.getsockopt(m_Handle, optionLevel, optionName, optionValue, ref optionLength);
2759 UpdateStatusAfterSocketError(ex);
2760 if (s_LoggingEnabled)
2762 Logging.Exception(Logging.Sockets,
this,
"GetSocketOption", ex);
2781 byte[] array =
new byte[optionLength];
2782 int optionLength2 = optionLength;
2783 SocketError socketError = UnsafeNclNativeMethods.OSSOCK.getsockopt(m_Handle, optionLevel, optionName, array, ref optionLength2);
2787 UpdateStatusAfterSocketError(ex);
2788 if (s_LoggingEnabled)
2790 Logging.Exception(Logging.Sockets,
this,
"GetSocketOption", ex);
2794 if (optionLength != optionLength2)
2796 byte[] array2 =
new byte[optionLength2];
2829 IntPtr intPtr = m_Handle.DangerousGetHandle();
2835 TimeValue socketTime =
default(TimeValue);
2837 if (microSeconds != -1)
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);
2844 num = UnsafeNclNativeMethods.OSSOCK.select(0, (mode ==
SelectMode.SelectRead) ? array :
null, (mode ==
SelectMode.SelectWrite) ? array :
null, (mode ==
SelectMode.SelectError) ? array :
null,
IntPtr.
Zero);
2849 UpdateStatusAfterSocketError(ex);
2850 if (s_LoggingEnabled)
2852 Logging.Exception(Logging.Sockets,
this,
"Poll", ex);
2856 if ((
int)array[0] == 0)
2860 return array[1] == intPtr;
2872 if ((checkRead ==
null || checkRead.
Count == 0) && (checkWrite ==
null || checkWrite.
Count == 0) && (checkError ==
null || checkError.
Count == 0))
2876 if (checkRead !=
null && checkRead.
Count > 65536)
2880 if (checkWrite !=
null && checkWrite.
Count > 65536)
2884 if (checkError !=
null && checkError.
Count > 65536)
2888 IntPtr[] array = SocketListToFileDescriptorSet(checkRead);
2889 IntPtr[] array2 = SocketListToFileDescriptorSet(checkWrite);
2890 IntPtr[] array3 = SocketListToFileDescriptorSet(checkError);
2892 if (microSeconds != -1)
2894 TimeValue socketTime =
default(TimeValue);
2895 MicrosecondsToTimeValue((uint)microSeconds, ref socketTime);
2896 num = UnsafeNclNativeMethods.OSSOCK.select(0, array, array2, array3, ref socketTime);
2900 num = UnsafeNclNativeMethods.OSSOCK.select(0, array, array2, array3,
IntPtr.
Zero);
2906 SelectFileDescriptor(checkRead, array);
2907 SelectFileDescriptor(checkWrite, array2);
2908 SelectFileDescriptor(checkError, array3);
2920 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
2937 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
2940 if (s_LoggingEnabled)
2942 Logging.Enter(Logging.Sockets,
this,
"BeginConnect", remoteEP);
2948 if (remoteEP ==
null)
2957 if (dnsEndPoint !=
null)
2965 if (CanUseConnectEx(remoteEP))
2967 return BeginConnectEx(remoteEP, flowContext:
true, callback, state);
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)
2977 Logging.Exit(Logging.Sockets,
this,
"BeginConnect", connectAsyncResult);
2979 return connectAsyncResult;
2989 if (s_LoggingEnabled)
2991 Logging.Enter(Logging.Sockets,
this,
"DuplicateAndClose",
null);
2997 ExceptionHelper.UnrestrictedSocketPermission.Demand();
3002 fixed (
byte* pinnedBuffer = protocolInformation)
3004 socketError = (
SocketError)UnsafeNclNativeMethods.OSSOCK.WSADuplicateSocket(m_Handle, (uint)targetProcessId, pinnedBuffer);
3006 if (socketError != 0)
3009 if (s_LoggingEnabled)
3011 Logging.Exception(Logging.Sockets,
this,
"DuplicateAndClose", ex);
3017 result.IsListening = isListening;
3019 result.RemoteEndPoint = m_RemoteEndPoint;
3021 if (s_LoggingEnabled)
3023 Logging.Exit(Logging.Sockets,
this,
"DuplicateAndClose",
null);
3030 if (CanUseConnectEx(remoteEP))
3032 return BeginConnectEx(remoteEP, flowContext:
false, callback, state);
3035 SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP2);
3036 ConnectAsyncResult connectAsyncResult =
new ConnectAsyncResult(
this, remoteEP2, state, callback);
3037 DoBeginConnect(remoteEP2, socketAddress, connectAsyncResult);
3038 return connectAsyncResult;
3041 private void DoBeginConnect(EndPoint endPointSnapshot, SocketAddress socketAddress, LazyAsyncResult asyncResult)
3043 EndPoint rightEndPoint = m_RightEndPoint;
3044 if (m_AcceptQueueOrConnectResult !=
null)
3048 m_AcceptQueueOrConnectResult = asyncResult;
3049 if (!SetAsyncEventSelect(AsyncEventBits.FdConnect))
3051 m_AcceptQueueOrConnectResult =
null;
3052 throw new ObjectDisposedException(GetType().FullName);
3054 IntPtr socketHandle = m_Handle.DangerousGetHandle();
3055 if (m_RightEndPoint ==
null)
3057 m_RightEndPoint = endPointSnapshot;
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)
3075 asyncResult.ErrorCode = (int)socketError;
3081 UnsetAsyncEventSelect();
3086 asyncResult.InvokeCallback();
3090 m_RightEndPoint = rightEndPoint;
3091 SocketException ex =
new SocketException(socketError);
3092 UpdateStatusAfterSocketError(ex);
3093 m_AcceptQueueOrConnectResult =
null;
3094 if (s_LoggingEnabled)
3096 Logging.Exception(Logging.Sockets,
this,
"BeginConnect", ex);
3101 private bool CanUseConnectEx(EndPoint remoteEP)
3103 if (socketType ==
SocketType.Stream && (m_RightEndPoint !=
null || remoteEP.GetType() == typeof(IPEndPoint)))
3107 return m_IsDisconnected;
3114 private void ConnectCallback()
3116 LazyAsyncResult lazyAsyncResult = (LazyAsyncResult)m_AcceptQueueOrConnectResult;
3117 if (!lazyAsyncResult.InternalPeekCompleted)
3119 NetworkEvents networkEvents =
default(NetworkEvents);
3120 networkEvents.Events = AsyncEventBits.FdConnect;
3122 object result =
null;
3129 socketError = UnsafeNclNativeMethods.OSSOCK.WSAEnumNetworkEvents(m_Handle, m_AsyncEvent.
SafeWaitHandle, ref networkEvents);
3131 UnsetAsyncEventSelect();
3133 catch (ObjectDisposedException)
3143 catch (Exception ex2)
3145 if (NclUtilities.IsFatal(ex2))
3151 if (!lazyAsyncResult.InternalPeekCompleted)
3153 lazyAsyncResult.ErrorCode = (int)socketError;
3154 lazyAsyncResult.InvokeCallback(result);
3171 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
3174 if (s_LoggingEnabled)
3176 Logging.Enter(Logging.Sockets,
this,
"BeginConnect", host);
3186 if (!ValidationHelper.ValidateTcpPort(port))
3198 MultipleAddressConnectAsyncResult multipleAddressConnectAsyncResult =
new MultipleAddressConnectAsyncResult(
null, port,
this, state, requestCallback);
3199 multipleAddressConnectAsyncResult.StartPostingAsyncOp(lockCapture:
false);
3200 IAsyncResult asyncResult =
Dns.UnsafeBeginGetHostAddresses(host, DnsCallback, multipleAddressConnectAsyncResult);
3203 multipleAddressConnectAsyncResult.InvokeCallback();
3205 multipleAddressConnectAsyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
3206 if (s_LoggingEnabled)
3208 Logging.Exit(Logging.Sockets,
this,
"BeginConnect", multipleAddressConnectAsyncResult);
3210 return multipleAddressConnectAsyncResult;
3227 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
3230 if (s_LoggingEnabled)
3232 Logging.Enter(Logging.Sockets,
this,
"BeginConnect", address);
3238 if (address ==
null)
3242 if (!ValidationHelper.ValidateTcpPort(port))
3251 if (s_LoggingEnabled)
3253 Logging.Exit(Logging.Sockets,
this,
"BeginConnect", asyncResult);
3272 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
3275 if (s_LoggingEnabled)
3277 Logging.Enter(Logging.Sockets,
this,
"BeginConnect", addresses);
3283 if (addresses ==
null)
3287 if (addresses.Length == 0)
3289 throw new ArgumentException(SR.GetString(
"net_invalidAddressList"),
"addresses");
3291 if (!ValidationHelper.ValidateTcpPort(port))
3303 MultipleAddressConnectAsyncResult multipleAddressConnectAsyncResult =
new MultipleAddressConnectAsyncResult(addresses, port,
this, state, requestCallback);
3304 multipleAddressConnectAsyncResult.StartPostingAsyncOp(lockCapture:
false);
3305 if (DoMultipleAddressConnectCallback(PostOneBeginConnect(multipleAddressConnectAsyncResult), multipleAddressConnectAsyncResult))
3307 multipleAddressConnectAsyncResult.InvokeCallback();
3309 multipleAddressConnectAsyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
3310 if (s_LoggingEnabled)
3312 Logging.Exit(Logging.Sockets,
this,
"BeginConnect", multipleAddressConnectAsyncResult);
3314 return multipleAddressConnectAsyncResult;
3326 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
3329 DisconnectOverlappedAsyncResult disconnectOverlappedAsyncResult =
new DisconnectOverlappedAsyncResult(
this, state, callback);
3330 disconnectOverlappedAsyncResult.StartPostingAsyncOp(lockCapture:
false);
3331 DoBeginDisconnect(reuseSocket, disconnectOverlappedAsyncResult);
3332 disconnectOverlappedAsyncResult.FinishPostingAsyncOp();
3333 return disconnectOverlappedAsyncResult;
3336 private void DoBeginDisconnect(
bool reuseSocket, DisconnectOverlappedAsyncResult asyncResult)
3338 if (s_LoggingEnabled)
3340 Logging.Enter(Logging.Sockets,
this,
"BeginDisconnect",
null);
3346 asyncResult.SetUnmanagedStructures(
null);
3348 if (!DisconnectEx(m_Handle, asyncResult.OverlappedHandle, reuseSocket ? 2 : 0, 0))
3354 SetToDisconnected();
3355 m_RemoteEndPoint =
null;
3357 socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
3358 if (socketError != 0)
3360 SocketException ex =
new SocketException(socketError);
3361 UpdateStatusAfterSocketError(ex);
3362 if (s_LoggingEnabled)
3364 Logging.Exception(Logging.Sockets,
this,
"BeginDisconnect", ex);
3368 if (s_LoggingEnabled)
3370 Logging.Exit(Logging.Sockets,
this,
"BeginDisconnect", asyncResult);
3382 if (s_LoggingEnabled)
3384 Logging.Enter(Logging.Sockets,
this,
"Disconnect",
null);
3391 if (!DisconnectEx_Blocking(m_Handle.DangerousGetHandle(),
IntPtr.
Zero, reuseSocket ? 2 : 0, 0))
3395 if (socketError != 0)
3398 UpdateStatusAfterSocketError(ex);
3399 if (s_LoggingEnabled)
3401 Logging.Exception(Logging.Sockets,
this,
"Disconnect", ex);
3405 SetToDisconnected();
3406 m_RemoteEndPoint =
null;
3407 if (s_LoggingEnabled)
3409 Logging.Exit(Logging.Sockets,
this,
"Disconnect",
null);
3425 if (s_LoggingEnabled)
3427 Logging.Enter(Logging.Sockets,
this,
"EndConnect", asyncResult);
3433 if (asyncResult ==
null)
3437 LazyAsyncResult lazyAsyncResult =
null;
3439 ConnectOverlappedAsyncResult connectOverlappedAsyncResult = asyncResult as ConnectOverlappedAsyncResult;
3440 if (connectOverlappedAsyncResult ==
null)
3442 MultipleAddressConnectAsyncResult multipleAddressConnectAsyncResult = asyncResult as MultipleAddressConnectAsyncResult;
3443 if (multipleAddressConnectAsyncResult ==
null)
3445 ConnectAsyncResult connectAsyncResult = asyncResult as ConnectAsyncResult;
3446 if (connectAsyncResult !=
null)
3448 endPoint = connectAsyncResult.RemoteEndPoint;
3449 lazyAsyncResult = connectAsyncResult;
3454 endPoint = multipleAddressConnectAsyncResult.RemoteEndPoint;
3455 lazyAsyncResult = multipleAddressConnectAsyncResult;
3460 endPoint = connectOverlappedAsyncResult.RemoteEndPoint;
3461 lazyAsyncResult = connectOverlappedAsyncResult;
3463 if (lazyAsyncResult ==
null || lazyAsyncResult.AsyncObject !=
this)
3465 throw new ArgumentException(SR.GetString(
"net_io_invalidasyncresult"),
"asyncResult");
3467 if (lazyAsyncResult.EndCalled)
3471 lazyAsyncResult.InternalWaitForCompletion();
3472 lazyAsyncResult.EndCalled =
true;
3473 m_AcceptQueueOrConnectResult =
null;
3474 if (lazyAsyncResult.Result is
Exception)
3476 if (s_LoggingEnabled)
3478 Logging.
Exception(Logging.Sockets,
this,
"EndConnect", (
Exception)lazyAsyncResult.Result);
3480 throw (
Exception)lazyAsyncResult.Result;
3482 if (lazyAsyncResult.ErrorCode != 0)
3485 UpdateStatusAfterSocketError(ex);
3486 if (s_LoggingEnabled)
3488 Logging.Exception(Logging.Sockets,
this,
"EndConnect", ex);
3492 if (s_LoggingEnabled)
3495 Logging.Exit(Logging.Sockets,
this,
"EndConnect",
"");
3513 if (s_LoggingEnabled)
3515 Logging.Enter(Logging.Sockets,
this,
"EndDisconnect", asyncResult);
3521 if (asyncResult ==
null)
3525 LazyAsyncResult lazyAsyncResult = asyncResult as LazyAsyncResult;
3526 if (lazyAsyncResult ==
null || lazyAsyncResult.AsyncObject !=
this)
3528 throw new ArgumentException(SR.GetString(
"net_io_invalidasyncresult"),
"asyncResult");
3530 if (lazyAsyncResult.EndCalled)
3534 lazyAsyncResult.InternalWaitForCompletion();
3535 lazyAsyncResult.EndCalled =
true;
3536 if (lazyAsyncResult.ErrorCode != 0)
3539 UpdateStatusAfterSocketError(ex);
3540 if (s_LoggingEnabled)
3542 Logging.Exception(Logging.Sockets,
this,
"EndDisconnect", ex);
3546 if (s_LoggingEnabled)
3548 Logging.Exit(Logging.Sockets,
this,
"EndDisconnect",
null);
3569 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
3574 if (errorCode != 0 && errorCode !=
SocketError.IOPending)
3599 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
3602 if (s_LoggingEnabled)
3604 Logging.Enter(Logging.Sockets,
this,
"BeginSend",
"");
3614 if (offset < 0 || offset > buffer.Length)
3618 if (size < 0 || size > buffer.Length - offset)
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)
3627 overlappedAsyncResult =
null;
3631 overlappedAsyncResult.FinishPostingAsyncOp(ref Caches.SendClosureCache);
3633 if (s_LoggingEnabled)
3635 Logging.Exit(Logging.Sockets,
this,
"BeginSend", overlappedAsyncResult);
3637 return overlappedAsyncResult;
3642 if (s_LoggingEnabled)
3644 Logging.Enter(Logging.Sockets,
this,
"UnsafeBeginSend",
"");
3650 OverlappedAsyncResult overlappedAsyncResult =
new OverlappedAsyncResult(
this, state, callback);
3651 SocketError socketError = DoBeginSend(buffer, offset, size, socketFlags, overlappedAsyncResult);
3652 if (socketError != 0 && socketError !=
SocketError.IOPending)
3654 throw new SocketException(socketError);
3656 if (s_LoggingEnabled)
3658 Logging.Exit(Logging.Sockets,
this,
"UnsafeBeginSend", overlappedAsyncResult);
3660 return overlappedAsyncResult;
3663 private SocketError DoBeginSend(
byte[] buffer,
int offset,
int size,
SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
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)
3677 socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
3679 if (socketError != 0)
3681 asyncResult.ExtractCache(ref Caches.SendOverlappedCache);
3682 UpdateStatusAfterSocketError(socketError);
3683 if (s_LoggingEnabled)
3685 Logging.Exception(Logging.Sockets,
this,
"BeginSend",
new SocketException(socketError));
3703 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
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;
3713 private void DoBeginSendFile(
string fileName,
byte[] preBuffer,
byte[] postBuffer,
TransmitFileOptions flags, TransmitFileOverlappedAsyncResult asyncResult)
3715 if (s_LoggingEnabled)
3717 Logging.Enter(Logging.Sockets,
this,
"BeginSendFile",
"");
3729 throw new NotSupportedException(SR.GetString(
"net_notconnected"));
3732 if (fileName !=
null && fileName.Length > 0)
3737 if (fileStream !=
null)
3739 ExceptionHelper.UnmanagedPermission.Assert();
3752 asyncResult.SetUnmanagedStructures(preBuffer, postBuffer, fileStream, flags, ref Caches.SendOverlappedCache);
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));
3759 errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode);
3763 asyncResult.ExtractCache(ref Caches.SendOverlappedCache);
3764 SocketException ex =
new SocketException(errorCode);
3765 UpdateStatusAfterSocketError(ex);
3766 if (s_LoggingEnabled)
3768 Logging.Exception(Logging.Sockets,
this,
"BeginSendFile", ex);
3772 if (s_LoggingEnabled)
3774 Logging.Exit(Logging.Sockets,
this,
"BeginSendFile", errorCode);
3790 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
3795 if (errorCode != 0 && errorCode !=
SocketError.IOPending)
3815 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
3818 if (s_LoggingEnabled)
3820 Logging.Enter(Logging.Sockets,
this,
"BeginSend",
"");
3826 if (buffers ==
null)
3830 if (buffers.Count == 0)
3832 throw new ArgumentException(SR.GetString(
"net_sockets_zerolist",
"buffers"),
"buffers");
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)
3840 overlappedAsyncResult =
null;
3842 if (s_LoggingEnabled)
3844 Logging.Exit(Logging.Sockets,
this,
"BeginSend", overlappedAsyncResult);
3846 return overlappedAsyncResult;
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)
3863 socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
3865 if (socketError != 0)
3867 asyncResult.ExtractCache(ref Caches.SendOverlappedCache);
3868 UpdateStatusAfterSocketError(socketError);
3869 if (s_LoggingEnabled)
3871 Logging.Exception(Logging.Sockets,
this,
"BeginSend",
new SocketException(socketError));
3891 int result =
EndSend(asyncResult, out errorCode);
3913 if (s_LoggingEnabled)
3915 Logging.Enter(Logging.Sockets,
this,
"EndSend", asyncResult);
3921 if (asyncResult ==
null)
3925 OverlappedAsyncResult overlappedAsyncResult = asyncResult as OverlappedAsyncResult;
3926 if (overlappedAsyncResult ==
null || overlappedAsyncResult.AsyncObject !=
this)
3928 throw new ArgumentException(SR.GetString(
"net_io_invalidasyncresult"),
"asyncResult");
3930 if (overlappedAsyncResult.EndCalled)
3934 int num = (int)overlappedAsyncResult.InternalWaitForCompletion();
3935 overlappedAsyncResult.EndCalled =
true;
3936 overlappedAsyncResult.ExtractCache(ref Caches.SendOverlappedCache);
3937 if (s_PerfCountersEnabled && num > 0)
3939 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, num);
3942 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
3945 errorCode = (
SocketError)overlappedAsyncResult.ErrorCode;
3948 UpdateStatusAfterSocketError(errorCode);
3949 if (s_LoggingEnabled)
3951 Logging.Exception(Logging.Sockets,
this,
"EndSend",
new SocketException(errorCode));
3952 Logging.Exit(Logging.Sockets,
this,
"EndSend", 0);
3956 if (s_LoggingEnabled)
3958 Logging.Exit(Logging.Sockets,
this,
"EndSend", num);
3976 if (s_LoggingEnabled)
3978 Logging.Enter(Logging.Sockets,
this,
"EndSendFile", asyncResult);
3984 if (asyncResult ==
null)
3988 TransmitFileOverlappedAsyncResult transmitFileOverlappedAsyncResult = asyncResult as TransmitFileOverlappedAsyncResult;
3989 if (transmitFileOverlappedAsyncResult ==
null || transmitFileOverlappedAsyncResult.AsyncObject !=
this)
3991 throw new ArgumentException(SR.GetString(
"net_io_invalidasyncresult"),
"asyncResult");
3993 if (transmitFileOverlappedAsyncResult.EndCalled)
3997 transmitFileOverlappedAsyncResult.InternalWaitForCompletion();
3998 transmitFileOverlappedAsyncResult.EndCalled =
true;
3999 transmitFileOverlappedAsyncResult.ExtractCache(ref Caches.SendOverlappedCache);
4002 SetToDisconnected();
4003 m_RemoteEndPoint =
null;
4005 if (transmitFileOverlappedAsyncResult.ErrorCode != 0)
4008 UpdateStatusAfterSocketError(ex);
4009 if (s_LoggingEnabled)
4011 Logging.Exception(Logging.Sockets,
this,
"EndSendFile", ex);
4015 if (s_LoggingEnabled)
4017 Logging.Exit(Logging.Sockets,
this,
"EndSendFile",
"");
4041 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
4044 if (s_LoggingEnabled)
4046 Logging.Enter(Logging.Sockets,
this,
"BeginSendTo",
"");
4056 if (remoteEP ==
null)
4060 if (offset < 0 || offset > buffer.Length)
4064 if (size < 0 || size > buffer.Length - offset)
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)
4076 Logging.Exit(Logging.Sockets,
this,
"BeginSendTo", overlappedAsyncResult);
4078 return overlappedAsyncResult;
4081 private void DoBeginSendTo(
byte[] buffer,
int offset,
int size,
SocketFlags socketFlags,
EndPoint endPointSnapshot,
SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
4083 EndPoint rightEndPoint = m_RightEndPoint;
4087 asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, pinSocketAddress:
false, ref Caches.SendOverlappedCache);
4088 if (m_RightEndPoint ==
null)
4090 m_RightEndPoint = endPointSnapshot;
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)
4098 catch (ObjectDisposedException)
4100 m_RightEndPoint = rightEndPoint;
4105 socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
4107 if (socketError != 0)
4109 m_RightEndPoint = rightEndPoint;
4110 asyncResult.ExtractCache(ref Caches.SendOverlappedCache);
4111 SocketException ex2 =
new SocketException(socketError);
4112 UpdateStatusAfterSocketError(ex2);
4113 if (s_LoggingEnabled)
4115 Logging.Exception(Logging.Sockets,
this,
"BeginSendTo", ex2);
4134 if (s_LoggingEnabled)
4136 Logging.Enter(Logging.Sockets,
this,
"EndSendTo", asyncResult);
4142 if (asyncResult ==
null)
4146 OverlappedAsyncResult overlappedAsyncResult = asyncResult as OverlappedAsyncResult;
4147 if (overlappedAsyncResult ==
null || overlappedAsyncResult.AsyncObject !=
this)
4149 throw new ArgumentException(SR.GetString(
"net_io_invalidasyncresult"),
"asyncResult");
4151 if (overlappedAsyncResult.EndCalled)
4155 int num = (int)overlappedAsyncResult.InternalWaitForCompletion();
4156 overlappedAsyncResult.EndCalled =
true;
4157 overlappedAsyncResult.ExtractCache(ref Caches.SendOverlappedCache);
4158 if (s_PerfCountersEnabled && num > 0)
4160 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, num);
4163 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
4166 if (overlappedAsyncResult.ErrorCode != 0)
4169 UpdateStatusAfterSocketError(ex);
4170 if (s_LoggingEnabled)
4172 Logging.Exception(Logging.Sockets,
this,
"EndSendTo", ex);
4176 if (s_LoggingEnabled)
4178 Logging.Exit(Logging.Sockets,
this,
"EndSendTo", num);
4201 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
4206 if (errorCode != 0 && errorCode !=
SocketError.IOPending)
4232 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
4235 if (s_LoggingEnabled)
4237 Logging.Enter(Logging.Sockets,
this,
"BeginReceive",
"");
4247 if (offset < 0 || offset > buffer.Length)
4251 if (size < 0 || size > buffer.Length - offset)
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)
4260 overlappedAsyncResult =
null;
4264 overlappedAsyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
4266 if (s_LoggingEnabled)
4268 Logging.Exit(Logging.Sockets,
this,
"BeginReceive", overlappedAsyncResult);
4270 return overlappedAsyncResult;
4275 if (s_LoggingEnabled)
4277 Logging.Enter(Logging.Sockets,
this,
"UnsafeBeginReceive",
"");
4283 OverlappedAsyncResult overlappedAsyncResult =
new OverlappedAsyncResult(
this, state, callback);
4284 DoBeginReceive(buffer, offset, size, socketFlags, overlappedAsyncResult);
4285 if (s_LoggingEnabled)
4287 Logging.Exit(Logging.Sockets,
this,
"UnsafeBeginReceive", overlappedAsyncResult);
4289 return overlappedAsyncResult;
4292 private SocketError DoBeginReceive(
byte[] buffer,
int offset,
int size,
SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
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)
4306 socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
4308 if (socketError != 0)
4310 asyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4311 UpdateStatusAfterSocketError(socketError);
4312 if (s_LoggingEnabled)
4314 Logging.Exception(Logging.Sockets,
this,
"BeginReceive",
new SocketException(socketError));
4316 asyncResult.InvokeCallback(
new SocketException(socketError));
4332 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
4337 if (errorCode != 0 && errorCode !=
SocketError.IOPending)
4356 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
4359 if (s_LoggingEnabled)
4361 Logging.Enter(Logging.Sockets,
this,
"BeginReceive",
"");
4367 if (buffers ==
null)
4371 if (buffers.Count == 0)
4373 throw new ArgumentException(SR.GetString(
"net_sockets_zerolist",
"buffers"),
"buffers");
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)
4380 overlappedAsyncResult =
null;
4384 overlappedAsyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
4386 if (s_LoggingEnabled)
4388 Logging.Exit(Logging.Sockets,
this,
"BeginReceive", overlappedAsyncResult);
4390 return overlappedAsyncResult;
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)
4407 socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
4409 if (socketError != 0)
4411 asyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4412 UpdateStatusAfterSocketError(socketError);
4413 if (s_LoggingEnabled)
4415 Logging.Exception(Logging.Sockets,
this,
"BeginReceive",
new SocketException(socketError));
4435 int result =
EndReceive(asyncResult, out errorCode);
4457 if (s_LoggingEnabled)
4459 Logging.Enter(Logging.Sockets,
this,
"EndReceive", asyncResult);
4465 if (asyncResult ==
null)
4469 OverlappedAsyncResult overlappedAsyncResult = asyncResult as OverlappedAsyncResult;
4470 if (overlappedAsyncResult ==
null || overlappedAsyncResult.AsyncObject !=
this)
4472 throw new ArgumentException(SR.GetString(
"net_io_invalidasyncresult"),
"asyncResult");
4474 if (overlappedAsyncResult.EndCalled)
4478 int num = (int)overlappedAsyncResult.InternalWaitForCompletion();
4479 overlappedAsyncResult.EndCalled =
true;
4480 overlappedAsyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4481 if (s_PerfCountersEnabled && num > 0)
4483 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, num);
4486 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
4489 errorCode = (
SocketError)overlappedAsyncResult.ErrorCode;
4492 UpdateStatusAfterSocketError(errorCode);
4493 if (s_LoggingEnabled)
4495 Logging.Exception(Logging.Sockets,
this,
"EndReceive",
new SocketException(errorCode));
4496 Logging.Exit(Logging.Sockets,
this,
"EndReceive", 0);
4500 if (s_LoggingEnabled)
4502 Logging.Exit(Logging.Sockets,
this,
"EndReceive", num);
4529 if (s_LoggingEnabled)
4531 Logging.Enter(Logging.Sockets,
this,
"BeginReceiveMessageFrom",
"");
4541 if (remoteEP ==
null)
4545 if (!CanTryAddressFamily(remoteEP.AddressFamily))
4547 throw new ArgumentException(SR.GetString(
"net_InvalidEndPointAddressFamily", remoteEP.AddressFamily, addressFamily),
"remoteEP");
4549 if (offset < 0 || offset > buffer.Length)
4553 if (size < 0 || size > buffer.Length - offset)
4557 if (m_RightEndPoint ==
null)
4561 ReceiveMessageOverlappedAsyncResult receiveMessageOverlappedAsyncResult =
new ReceiveMessageOverlappedAsyncResult(
this, state, callback);
4562 receiveMessageOverlappedAsyncResult.StartPostingAsyncOp(lockCapture:
false);
4563 EndPoint rightEndPoint = m_RightEndPoint;
4564 SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP);
4568 receiveMessageOverlappedAsyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags, ref Caches.ReceiveOverlappedCache);
4569 receiveMessageOverlappedAsyncResult.SocketAddressOriginal = remoteEP.Serialize();
4570 SetReceivingPacketInformation();
4571 if (m_RightEndPoint ==
null)
4573 m_RightEndPoint = remoteEP;
4576 if (socketError != 0)
4587 m_RightEndPoint = rightEndPoint;
4592 socketError = receiveMessageOverlappedAsyncResult.CheckAsyncCallOverlappedResult(socketError);
4594 if (socketError != 0)
4596 m_RightEndPoint = rightEndPoint;
4597 receiveMessageOverlappedAsyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4599 UpdateStatusAfterSocketError(ex2);
4600 if (s_LoggingEnabled)
4602 Logging.Exception(Logging.Sockets,
this,
"BeginReceiveMessageFrom", ex2);
4606 receiveMessageOverlappedAsyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache);
4607 if (receiveMessageOverlappedAsyncResult.CompletedSynchronously && !receiveMessageOverlappedAsyncResult.SocketAddressOriginal.Equals(receiveMessageOverlappedAsyncResult.SocketAddress))
4611 remoteEP = remoteEP.Create(receiveMessageOverlappedAsyncResult.SocketAddress);
4617 if (s_LoggingEnabled)
4619 Logging.Exit(Logging.Sockets,
this,
"BeginReceiveMessageFrom", receiveMessageOverlappedAsyncResult);
4621 return receiveMessageOverlappedAsyncResult;
4641 if (s_LoggingEnabled)
4643 Logging.Enter(Logging.Sockets,
this,
"EndReceiveMessageFrom", asyncResult);
4649 if (endPoint ==
null)
4653 if (!CanTryAddressFamily(endPoint.AddressFamily))
4655 throw new ArgumentException(SR.GetString(
"net_InvalidEndPointAddressFamily", endPoint.AddressFamily, addressFamily),
"endPoint");
4657 if (asyncResult ==
null)
4661 ReceiveMessageOverlappedAsyncResult receiveMessageOverlappedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult;
4662 if (receiveMessageOverlappedAsyncResult ==
null || receiveMessageOverlappedAsyncResult.AsyncObject !=
this)
4664 throw new ArgumentException(SR.GetString(
"net_io_invalidasyncresult"),
"asyncResult");
4666 if (receiveMessageOverlappedAsyncResult.EndCalled)
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))
4679 endPoint = endPoint.Create(receiveMessageOverlappedAsyncResult.SocketAddress);
4685 if (s_PerfCountersEnabled && num > 0)
4687 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, num);
4690 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
4693 if (receiveMessageOverlappedAsyncResult.ErrorCode != 0 && receiveMessageOverlappedAsyncResult.ErrorCode != 10040)
4696 UpdateStatusAfterSocketError(ex);
4697 if (s_LoggingEnabled)
4699 Logging.Exception(Logging.Sockets,
this,
"EndReceiveMessageFrom", ex);
4703 socketFlags = receiveMessageOverlappedAsyncResult.m_flags;
4704 ipPacketInformation = receiveMessageOverlappedAsyncResult.m_IPPacketInformation;
4705 if (s_LoggingEnabled)
4707 Logging.Exit(Logging.Sockets,
this,
"EndReceiveMessageFrom", num);
4732 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
4735 if (s_LoggingEnabled)
4737 Logging.Enter(Logging.Sockets,
this,
"BeginReceiveFrom",
"");
4747 if (remoteEP ==
null)
4751 if (!CanTryAddressFamily(remoteEP.AddressFamily))
4753 throw new ArgumentException(SR.GetString(
"net_InvalidEndPointAddressFamily", remoteEP.AddressFamily, addressFamily),
"remoteEP");
4755 if (offset < 0 || offset > buffer.Length)
4759 if (size < 0 || size > buffer.Length - offset)
4763 if (m_RightEndPoint ==
null)
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))
4776 remoteEP = remoteEP.Create(overlappedAsyncResult.SocketAddress);
4782 if (s_LoggingEnabled)
4784 Logging.Exit(Logging.Sockets,
this,
"BeginReceiveFrom", overlappedAsyncResult);
4786 return overlappedAsyncResult;
4789 private void DoBeginReceiveFrom(
byte[] buffer,
int offset,
int size,
SocketFlags socketFlags,
EndPoint endPointSnapshot,
SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
4791 EndPoint rightEndPoint = m_RightEndPoint;
4795 asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, pinSocketAddress:
true, ref Caches.ReceiveOverlappedCache);
4796 asyncResult.SocketAddressOriginal = endPointSnapshot.
Serialize();
4797 if (m_RightEndPoint ==
null)
4799 m_RightEndPoint = endPointSnapshot;
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)
4807 catch (ObjectDisposedException)
4809 m_RightEndPoint = rightEndPoint;
4814 socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
4816 if (socketError != 0)
4818 m_RightEndPoint = rightEndPoint;
4819 asyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache);
4820 SocketException ex2 =
new SocketException(socketError);
4821 UpdateStatusAfterSocketError(ex2);
4822 if (s_LoggingEnabled)
4824 Logging.Exception(Logging.Sockets,
this,
"BeginReceiveFrom", ex2);
4844 if (s_LoggingEnabled)
4846 Logging.Enter(Logging.Sockets,
this,
"EndReceiveFrom", asyncResult);
4852 if (endPoint ==
null)
4856 if (!CanTryAddressFamily(endPoint.AddressFamily))
4858 throw new ArgumentException(SR.GetString(
"net_InvalidEndPointAddressFamily", endPoint.AddressFamily, addressFamily),
"endPoint");
4860 if (asyncResult ==
null)
4864 OverlappedAsyncResult overlappedAsyncResult = asyncResult as OverlappedAsyncResult;
4865 if (overlappedAsyncResult ==
null || overlappedAsyncResult.AsyncObject !=
this)
4867 throw new ArgumentException(SR.GetString(
"net_io_invalidasyncresult"),
"asyncResult");
4869 if (overlappedAsyncResult.EndCalled)
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))
4882 endPoint = endPoint.Create(overlappedAsyncResult.SocketAddress);
4888 if (s_PerfCountersEnabled && num > 0)
4890 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, num);
4893 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived);
4896 if (overlappedAsyncResult.ErrorCode != 0)
4899 UpdateStatusAfterSocketError(ex);
4900 if (s_LoggingEnabled)
4902 Logging.Exception(Logging.Sockets,
this,
"EndReceiveFrom", ex);
4906 if (s_LoggingEnabled)
4908 Logging.Exit(Logging.Sockets,
this,
"EndReceiveFrom", num);
4923 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
4930 if (s_LoggingEnabled)
4932 Logging.Enter(Logging.Sockets,
this,
"BeginAccept",
"");
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)
4944 Logging.Exit(Logging.Sockets,
this,
"BeginAccept", acceptAsyncResult);
4946 return acceptAsyncResult;
4949 private void DoBeginAccept(LazyAsyncResult asyncResult)
4951 if (m_RightEndPoint ==
null)
4961 Queue acceptQueue = GetAcceptQueue();
4964 if (acceptQueue.
Count == 0)
4966 SocketAddress socketAddress = m_RightEndPoint.
Serialize();
4967 InternalSetBlocking(desired:
false);
4968 SafeCloseSocket safeCloseSocket =
null;
4971 safeCloseSocket = SafeCloseSocket.Accept(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size);
4974 catch (ObjectDisposedException)
4982 asyncResult.Result = CreateAcceptSocket(safeCloseSocket, m_RightEndPoint.
Create(socketAddress), needCancelSelect:
false);
4986 asyncResult.ErrorCode = (int)socketError;
4988 InternalSetBlocking(desired:
true);
4993 acceptQueue.
Enqueue(asyncResult);
4994 if (!SetAsyncEventSelect(AsyncEventBits.FdAccept))
4997 throw new ObjectDisposedException(GetType().FullName);
5003 acceptQueue.
Enqueue(asyncResult);
5012 asyncResult.InvokeCallback();
5015 SocketException ex2 =
new SocketException(socketError);
5016 UpdateStatusAfterSocketError(ex2);
5017 if (s_LoggingEnabled)
5019 Logging.Exception(Logging.Sockets,
this,
"BeginAccept", ex2);
5024 private void CompleteAcceptResults(
object nullState)
5026 Queue acceptQueue = GetAcceptQueue();
5030 LazyAsyncResult lazyAsyncResult =
null;
5033 if (acceptQueue.
Count == 0)
5037 lazyAsyncResult = (LazyAsyncResult)acceptQueue.
Dequeue();
5038 if (acceptQueue.
Count == 0)
5045 lazyAsyncResult.InvokeCallback(
new SocketException(
SocketError.OperationAborted));
5058 private void AcceptCallback(
object nullState)
5061 Queue acceptQueue = GetAcceptQueue();
5064 LazyAsyncResult lazyAsyncResult =
null;
5066 SocketAddress socketAddress =
null;
5067 SafeCloseSocket safeCloseSocket =
null;
5068 Exception ex =
null;
5069 object result =
null;
5072 if (acceptQueue.
Count == 0)
5076 lazyAsyncResult = (LazyAsyncResult)acceptQueue.
Peek();
5079 socketAddress = m_RightEndPoint.
Serialize();
5082 safeCloseSocket = SafeCloseSocket.Accept(m_Handle, socketAddress.m_Buffer, ref socketAddress.m_Size);
5085 catch (ObjectDisposedException)
5089 catch (Exception ex3)
5091 if (NclUtilities.IsFatal(ex3))
5098 if (socketError ==
SocketError.WouldBlock && ex ==
null)
5102 m_AsyncEvent.
Reset();
5103 if (SetAsyncEventSelect(AsyncEventBits.FdAccept))
5108 catch (ObjectDisposedException)
5111 ex =
new ObjectDisposedException(GetType().FullName);
5119 result = CreateAcceptSocket(safeCloseSocket, m_RightEndPoint.
Create(socketAddress), needCancelSelect:
true);
5123 lazyAsyncResult.ErrorCode = (int)socketError;
5126 if (acceptQueue.
Count == 0)
5130 UnsetAsyncEventSelect();
5137 lazyAsyncResult.InvokeCallback(result);
5161 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
5164 return BeginAccept(
null, receiveSize, callback, state);
5179 [HostProtection(
SecurityAction.LinkDemand, ExternalThreading =
true)]
5182 if (s_LoggingEnabled)
5184 Logging.Enter(Logging.Sockets,
this,
"BeginAccept",
"");
5190 if (receiveSize < 0)
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)
5200 Logging.Exit(Logging.Sockets,
this,
"BeginAccept", acceptOverlappedAsyncResult);
5202 return acceptOverlappedAsyncResult;
5205 private void DoBeginAccept(
Socket acceptSocket,
int receiveSize, AcceptOverlappedAsyncResult asyncResult)
5207 if (m_RightEndPoint ==
null)
5215 if (acceptSocket ==
null)
5217 acceptSocket =
new Socket(addressFamily, socketType, protocolType);
5219 else if (acceptSocket.m_RightEndPoint !=
null)
5221 throw new InvalidOperationException(SR.GetString(
"net_sockets_namedmustnotbebound",
"acceptSocket"));
5223 asyncResult.AcceptSocket = acceptSocket;
5225 byte[] buffer =
new byte[receiveSize + num * 2];
5226 asyncResult.SetUnmanagedStructures(buffer, num);
5228 if (!AcceptEx(m_Handle, acceptSocket.m_Handle,
Marshal.
UnsafeAddrOfPinnedArrayElement((Array)asyncResult.Buffer, 0), receiveSize, num, num, out
int _, asyncResult.OverlappedHandle))
5232 errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode);
5235 SocketException ex =
new SocketException(errorCode);
5236 UpdateStatusAfterSocketError(ex);
5237 if (s_LoggingEnabled)
5239 Logging.Exception(Logging.Sockets,
this,
"BeginAccept", ex);
5259 if (s_LoggingEnabled)
5261 Logging.Enter(Logging.Sockets,
this,
"EndAccept", asyncResult);
5268 int bytesTransferred;
5269 if (asyncResult !=
null && asyncResult is AcceptOverlappedAsyncResult)
5271 return EndAccept(out buffer, out bytesTransferred, asyncResult);
5273 if (asyncResult ==
null)
5277 AcceptAsyncResult acceptAsyncResult = asyncResult as AcceptAsyncResult;
5278 if (acceptAsyncResult ==
null || acceptAsyncResult.AsyncObject !=
this)
5280 throw new ArgumentException(SR.GetString(
"net_io_invalidasyncresult"),
"asyncResult");
5282 if (acceptAsyncResult.EndCalled)
5286 object obj = acceptAsyncResult.InternalWaitForCompletion();
5287 acceptAsyncResult.EndCalled =
true;
5293 if (acceptAsyncResult.ErrorCode != 0)
5296 UpdateStatusAfterSocketError(ex2);
5297 if (s_LoggingEnabled)
5299 Logging.Exception(Logging.Sockets,
this,
"EndAccept", ex2);
5304 if (s_LoggingEnabled)
5307 Logging.Exit(Logging.Sockets,
this,
"EndAccept", obj);
5328 int bytesTransferred;
5329 Socket result =
EndAccept(out buffer2, out bytesTransferred, asyncResult);
5330 buffer =
new byte[bytesTransferred];
5331 Array.
Copy(buffer2, buffer, bytesTransferred);
5351 if (s_LoggingEnabled)
5353 Logging.Enter(Logging.Sockets,
this,
"EndAccept", asyncResult);
5359 if (asyncResult ==
null)
5363 AcceptOverlappedAsyncResult acceptOverlappedAsyncResult = asyncResult as AcceptOverlappedAsyncResult;
5364 if (acceptOverlappedAsyncResult ==
null || acceptOverlappedAsyncResult.AsyncObject !=
this)
5366 throw new ArgumentException(SR.GetString(
"net_io_invalidasyncresult"),
"asyncResult");
5368 if (acceptOverlappedAsyncResult.EndCalled)
5372 Socket socket = (
Socket)acceptOverlappedAsyncResult.InternalWaitForCompletion();
5373 bytesTransferred = acceptOverlappedAsyncResult.BytesTransferred;
5374 buffer = acceptOverlappedAsyncResult.Buffer;
5375 acceptOverlappedAsyncResult.EndCalled =
true;
5376 if (s_PerfCountersEnabled && bytesTransferred > 0)
5378 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, bytesTransferred);
5380 if (acceptOverlappedAsyncResult.ErrorCode != 0)
5383 UpdateStatusAfterSocketError(ex);
5384 if (s_LoggingEnabled)
5386 Logging.Exception(Logging.Sockets,
this,
"EndAccept", ex);
5390 if (s_LoggingEnabled)
5393 Logging.Exit(Logging.Sockets,
this,
"EndAccept", socket);
5404 if (s_LoggingEnabled)
5406 Logging.Enter(Logging.Sockets,
this,
"Shutdown", how);
5412 SocketError socketError = UnsafeNclNativeMethods.OSSOCK.shutdown(m_Handle, (
int)how);
5414 if (socketError != 0 && socketError !=
SocketError.NotSocket)
5417 UpdateStatusAfterSocketError(ex);
5418 if (s_LoggingEnabled)
5420 Logging.Exception(Logging.Sockets,
this,
"Shutdown", ex);
5424 SetToDisconnected();
5425 InternalSetBlocking(willBlockInternal);
5426 if (s_LoggingEnabled)
5428 Logging.Exit(Logging.Sockets,
this,
"Shutdown",
"");
5432 private void EnsureDynamicWinsockMethods()
5434 if (m_DynamicWinsockMethods ==
null)
5436 m_DynamicWinsockMethods = DynamicWinsockMethods.GetMethods(addressFamily, socketType, protocolType);
5440 private bool AcceptEx(SafeCloseSocket listenSocketHandle, SafeCloseSocket acceptSocketHandle,
IntPtr buffer,
int len,
int localAddressLength,
int remoteAddressLength, out
int bytesReceived,
SafeHandle overlapped)
5442 EnsureDynamicWinsockMethods();
5443 AcceptExDelegate @delegate = m_DynamicWinsockMethods.GetDelegate<AcceptExDelegate>(listenSocketHandle);
5444 return @delegate(listenSocketHandle, acceptSocketHandle, buffer, len, localAddressLength, remoteAddressLength, out bytesReceived, overlapped);
5447 internal void GetAcceptExSockaddrs(IntPtr buffer,
int receiveDataLength,
int localAddressLength,
int remoteAddressLength, out IntPtr localSocketAddress, out
int localSocketAddressLength, out IntPtr remoteSocketAddress, out
int remoteSocketAddressLength)
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);
5454 private bool DisconnectEx(SafeCloseSocket socketHandle,
SafeHandle overlapped,
int flags,
int reserved)
5456 EnsureDynamicWinsockMethods();
5457 DisconnectExDelegate @delegate = m_DynamicWinsockMethods.GetDelegate<DisconnectExDelegate>(socketHandle);
5458 return @delegate(socketHandle, overlapped, flags, reserved);
5461 private bool DisconnectEx_Blocking(IntPtr socketHandle, IntPtr overlapped,
int flags,
int reserved)
5463 EnsureDynamicWinsockMethods();
5464 DisconnectExDelegate_Blocking @delegate = m_DynamicWinsockMethods.GetDelegate<DisconnectExDelegate_Blocking>(m_Handle);
5465 return @delegate(socketHandle, overlapped, flags, reserved);
5468 private bool ConnectEx(SafeCloseSocket socketHandle, IntPtr socketAddress,
int socketAddressSize, IntPtr buffer,
int dataLength, out
int bytesSent,
SafeHandle overlapped)
5470 EnsureDynamicWinsockMethods();
5471 ConnectExDelegate @delegate = m_DynamicWinsockMethods.GetDelegate<ConnectExDelegate>(socketHandle);
5472 return @delegate(socketHandle, socketAddress, socketAddressSize, buffer, dataLength, out bytesSent, overlapped);
5475 private SocketError WSARecvMsg(SafeCloseSocket socketHandle, IntPtr msg, out
int bytesTransferred,
SafeHandle overlapped, IntPtr completionRoutine)
5477 EnsureDynamicWinsockMethods();
5478 WSARecvMsgDelegate @delegate = m_DynamicWinsockMethods.GetDelegate<WSARecvMsgDelegate>(socketHandle);
5479 return @delegate(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
5482 private SocketError WSARecvMsg_Blocking(IntPtr socketHandle, IntPtr msg, out
int bytesTransferred, IntPtr overlapped, IntPtr completionRoutine)
5484 EnsureDynamicWinsockMethods();
5485 WSARecvMsgDelegate_Blocking @delegate = m_DynamicWinsockMethods.GetDelegate<WSARecvMsgDelegate_Blocking>(m_Handle);
5486 return @delegate(socketHandle, msg, out bytesTransferred, overlapped, completionRoutine);
5489 private bool TransmitPackets(SafeCloseSocket socketHandle, IntPtr packetArray,
int elementCount,
int sendSize, SafeNativeOverlapped overlapped,
TransmitFileOptions flags)
5491 EnsureDynamicWinsockMethods();
5492 TransmitPacketsDelegate @delegate = m_DynamicWinsockMethods.GetDelegate<TransmitPacketsDelegate>(socketHandle);
5493 return @delegate(socketHandle, packetArray, elementCount, sendSize, overlapped, flags);
5496 private Queue GetAcceptQueue()
5498 if (m_AcceptQueueOrConnectResult ==
null)
5502 return (
Queue)m_AcceptQueueOrConnectResult;
5509 ExceptionHelper.UnmanagedPermission.Demand();
5513 private SocketAddress SnapshotAndSerialize(ref EndPoint remoteEP)
5515 IPEndPoint iPEndPoint = remoteEP as IPEndPoint;
5516 if (iPEndPoint !=
null)
5518 iPEndPoint = iPEndPoint.Snapshot();
5519 remoteEP = RemapIPEndPoint(iPEndPoint);
5521 return CallSerializeCheckDnsEndPoint(remoteEP);
5524 private SocketAddress CallSerializeCheckDnsEndPoint(EndPoint remoteEP)
5526 if (remoteEP is DnsEndPoint)
5528 throw new ArgumentException(SR.GetString(
"net_sockets_invalid_dnsendpoint",
"remoteEP"),
"remoteEP");
5530 return remoteEP.Serialize();
5533 private IPEndPoint RemapIPEndPoint(IPEndPoint input)
5535 if (input.AddressFamily ==
AddressFamily.InterNetwork && IsDualMode)
5537 return new IPEndPoint(input.Address.MapToIPv6(), input.Port);
5542 private SocketAddress CheckCacheRemote(ref EndPoint remoteEP,
bool isOverwrite)
5544 IPEndPoint iPEndPoint = remoteEP as IPEndPoint;
5545 if (iPEndPoint !=
null)
5547 iPEndPoint = iPEndPoint.Snapshot();
5548 remoteEP = RemapIPEndPoint(iPEndPoint);
5550 SocketAddress socketAddress = CallSerializeCheckDnsEndPoint(remoteEP);
5551 SocketAddress permittedRemoteAddress = m_PermittedRemoteAddress;
5552 if (permittedRemoteAddress !=
null && permittedRemoteAddress.Equals(socketAddress))
5554 return permittedRemoteAddress;
5556 if (iPEndPoint !=
null)
5558 SocketPermission socketPermission =
new SocketPermission(
NetworkAccess.Connect, Transport, iPEndPoint.Address.ToString(), iPEndPoint.Port);
5559 socketPermission.Demand();
5563 ExceptionHelper.UnmanagedPermission.Demand();
5565 if ((m_PermittedRemoteAddress ==
null) | isOverwrite)
5567 m_PermittedRemoteAddress = socketAddress;
5569 return socketAddress;
5572 internal static void InitializeSockets()
5576 lock (InternalSyncObject)
5580 WSAData lpWSAData =
default(WSAData);
5581 SocketError socketError = UnsafeNclNativeMethods.OSSOCK.WSAStartup(514, out lpWSAData);
5582 if (socketError != 0)
5584 throw new SocketException(socketError);
5588 SafeCloseSocket.InnerSafeCloseSocket innerSafeCloseSocket = UnsafeNclNativeMethods.OSSOCK.WSASocket(
AddressFamily.InterNetwork,
SocketType.Dgram,
ProtocolType.IP, IntPtr.Zero, 0u, (SocketConstructorFlags)0);
5589 if (innerSafeCloseSocket.IsInvalid)
5592 if (socketError ==
SocketError.AddressFamilyNotSupported)
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)
5602 if (socketError ==
SocketError.AddressFamilyNotSupported)
5607 innerSafeCloseSocket2.Close();
5610 s_OSSupportsIPv6 =
true;
5611 flag2 = SettingsSectionInternal.Section.Ipv6Enabled;
5613 s_SupportsIPv4 = flag;
5614 s_SupportsIPv6 = flag2;
5615 s_PerfCountersEnabled = NetworkingPerfCounters.Instance.Enabled;
5616 s_Initialized =
true;
5622 internal void InternalConnect(EndPoint remoteEP)
5624 EndPoint remoteEP2 = remoteEP;
5625 SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP2);
5626 DoConnect(remoteEP2, socketAddress);
5629 private void DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
5631 if (s_LoggingEnabled)
5633 Logging.Enter(Logging.Sockets,
this,
"Connect", endPointSnapshot);
5635 if (UnsafeNclNativeMethods.OSSOCK.WSAConnect(m_Handle.DangerousGetHandle(), socketAddress.m_Buffer, socketAddress.m_Size, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero) != 0)
5637 SocketException ex =
new SocketException(endPointSnapshot);
5638 UpdateStatusAfterSocketError(ex);
5639 if (s_LoggingEnabled)
5641 Logging.Exception(Logging.Sockets,
this,
"Connect", ex);
5645 if (m_RightEndPoint ==
null)
5647 m_RightEndPoint = endPointSnapshot;
5650 if (s_LoggingEnabled)
5653 Logging.Exit(Logging.Sockets,
this,
"Connect",
"");
5668 if (s_LoggingEnabled)
5670 Logging.Enter(Logging.Sockets,
this,
"Dispose",
null);
5675 if (NclUtilities.IsFatal(exception))
5689 if (s_LoggingEnabled)
5691 Logging.Exit(Logging.Sockets,
this,
"Dispose",
null);
5696 if (NclUtilities.IsFatal(exception2))
5703 SetToDisconnected();
5704 AsyncEventBits asyncEventBits = AsyncEventBits.FdNone;
5705 if (m_BlockEventBits != 0)
5707 UnsetAsyncEventSelect();
5708 if (m_BlockEventBits == AsyncEventBits.FdConnect)
5710 LazyAsyncResult lazyAsyncResult = m_AcceptQueueOrConnectResult as LazyAsyncResult;
5711 if (lazyAsyncResult !=
null && !lazyAsyncResult.InternalPeekCompleted)
5713 asyncEventBits = AsyncEventBits.FdConnect;
5716 else if (m_BlockEventBits == AsyncEventBits.FdAccept)
5718 Queue queue = m_AcceptQueueOrConnectResult as
Queue;
5719 if (queue !=
null && queue.Count != 0)
5721 asyncEventBits = AsyncEventBits.FdAccept;
5727 int optionValue = m_CloseTimeout;
5728 if (optionValue == 0)
5734 if (!willBlock || !willBlockInternal)
5737 SocketError socketError = UnsafeNclNativeMethods.OSSOCK.ioctlsocket(m_Handle, -2147195266, ref argp);
5739 if (optionValue < 0)
5741 m_Handle.CloseAsIs();
5745 SocketError socketError = UnsafeNclNativeMethods.OSSOCK.shutdown(m_Handle, 1);
5750 else if (UnsafeNclNativeMethods.OSSOCK.recv(m_Handle.DangerousGetHandle(),
null, 0,
SocketFlags.None) != 0)
5757 if (UnsafeNclNativeMethods.OSSOCK.ioctlsocket(m_Handle, 1074030207, ref argp2) != 0 || argp2 != 0)
5763 m_Handle.CloseAsIs();
5772 if (m_Caches !=
null)
5774 OverlappedCache.InterlockedFree(ref m_Caches.SendOverlappedCache);
5775 OverlappedCache.InterlockedFree(ref m_Caches.ReceiveOverlappedCache);
5777 switch (asyncEventBits)
5779 case AsyncEventBits.FdConnect:
5782 case AsyncEventBits.FdAccept:
5786 if (m_AsyncEvent !=
null)
5788 m_AsyncEvent.
Close();
5807 if (!CleanedUp && !m_Handle.IsInvalid)
5811 UnsafeNclNativeMethods.OSSOCK.shutdown(m_Handle, (
int)how);
5819 internal void SetReceivingPacketInformation()
5821 if (!m_ReceivingPacketInformation)
5823 IPAddress iPAddress = (m_RightEndPoint as IPEndPoint)?.Address;
5824 if (addressFamily ==
AddressFamily.InterNetwork || (iPAddress !=
null && IsDualMode && (iPAddress.IsIPv4MappedToIPv6 || iPAddress.Equals(IPAddress.IPv6Any))))
5828 if (addressFamily ==
AddressFamily.InterNetworkV6 && (iPAddress ==
null || !iPAddress.IsIPv4MappedToIPv6))
5832 m_ReceivingPacketInformation =
true;
5838 if (silent && (CleanedUp || m_Handle.IsInvalid))
5845 socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(m_Handle, optionLevel, optionName, ref optionValue, 4);
5849 if (silent && m_Handle.IsInvalid)
5857 m_ReceivingPacketInformation =
false;
5859 if (silent || socketError !=
SocketError.SocketError)
5863 SocketException ex =
new SocketException();
5864 UpdateStatusAfterSocketError(ex);
5865 if (s_LoggingEnabled)
5867 Logging.Exception(Logging.Sockets,
this,
"SetSocketOption", ex);
5872 private void setMulticastOption(
SocketOptionName optionName, MulticastOption MR)
5874 IPMulticastRequest mreq =
default(IPMulticastRequest);
5875 mreq.MulticastAddress = (int)MR.Group.m_Address;
5876 if (MR.LocalAddress ==
null)
5878 int num = mreq.InterfaceAddress = IPAddress.HostToNetworkOrder(MR.InterfaceIndex);
5882 mreq.InterfaceAddress = (int)MR.LocalAddress.m_Address;
5884 SocketError socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(m_Handle,
SocketOptionLevel.IP, optionName, ref mreq, IPMulticastRequest.Size);
5887 SocketException ex =
new SocketException();
5888 UpdateStatusAfterSocketError(ex);
5889 if (s_LoggingEnabled)
5891 Logging.Exception(Logging.Sockets,
this,
"setMulticastOption", ex);
5897 private void setIPv6MulticastOption(
SocketOptionName optionName, IPv6MulticastOption MR)
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);
5905 SocketException ex =
new SocketException();
5906 UpdateStatusAfterSocketError(ex);
5907 if (s_LoggingEnabled)
5909 Logging.Exception(Logging.Sockets,
this,
"setIPv6MulticastOption", ex);
5915 private void setLingerOption(LingerOption lref)
5918 linger.OnOff = (ushort)(lref.Enabled ? 1 : 0);
5919 linger.Time = (ushort)lref.LingerTime;
5923 SocketException ex =
new SocketException();
5924 UpdateStatusAfterSocketError(ex);
5925 if (s_LoggingEnabled)
5927 Logging.Exception(Logging.Sockets,
this,
"setLingerOption", ex);
5933 private LingerOption getLingerOpt()
5936 int optionLength = 4;
5940 SocketException ex =
new SocketException();
5941 UpdateStatusAfterSocketError(ex);
5942 if (s_LoggingEnabled)
5944 Logging.Exception(Logging.Sockets,
this,
"getLingerOpt", ex);
5948 return new LingerOption(optionValue.OnOff != 0, optionValue.Time);
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);
5958 SocketException ex =
new SocketException();
5959 UpdateStatusAfterSocketError(ex);
5960 if (s_LoggingEnabled)
5962 Logging.Exception(Logging.Sockets,
this,
"getMulticastOpt", ex);
5966 IPAddress group =
new IPAddress(optionValue.MulticastAddress);
5967 IPAddress mcint =
new IPAddress(optionValue.InterfaceAddress);
5968 return new MulticastOption(group, mcint);
5971 private IPv6MulticastOption getIPv6MulticastOpt(
SocketOptionName optionName)
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);
5978 SocketException ex =
new SocketException();
5979 UpdateStatusAfterSocketError(ex);
5980 if (s_LoggingEnabled)
5982 Logging.Exception(Logging.Sockets,
this,
"getIPv6MulticastOpt", ex);
5986 return new IPv6MulticastOption(
new IPAddress(optionValue.MulticastAddress), optionValue.InterfaceIndex);
5989 private SocketError InternalSetBlocking(
bool desired, out
bool current)
5993 current = willBlock;
5996 int argp = (!desired) ? (-1) : 0;
6000 socketError = UnsafeNclNativeMethods.OSSOCK.ioctlsocket(m_Handle, -2147195266, ref argp);
6006 catch (ObjectDisposedException)
6012 willBlockInternal = (argp == 0);
6014 current = willBlockInternal;
6018 internal void InternalSetBlocking(
bool desired)
6020 InternalSetBlocking(desired, out
bool _);
6023 private static IntPtr[] SocketListToFileDescriptorSet(
IList socketList)
6025 if (socketList ==
null || socketList.
Count == 0)
6029 IntPtr[] array =
new IntPtr[socketList.
Count + 1];
6030 array[0] = (IntPtr)socketList.
Count;
6031 for (
int i = 0; i < socketList.
Count; i++)
6033 if (!(socketList[i] is
Socket))
6035 throw new ArgumentException(SR.GetString(
"net_sockets_select", socketList[i].GetType().FullName, typeof(
Socket).FullName),
"socketList");
6037 array[i + 1] = ((
Socket)socketList[i]).m_Handle.DangerousGetHandle();
6042 private static void SelectFileDescriptor(
IList socketList, IntPtr[] fileDescriptorSet)
6044 if (socketList !=
null && socketList.
Count != 0)
6046 if ((
int)fileDescriptorSet[0] == 0)
6054 for (
int i = 0; i < socketList.
Count; i++)
6058 for (j = 0; j < (int)fileDescriptorSet[0] && !(fileDescriptorSet[j + 1] == socket.m_Handle.DangerousGetHandle()); j++)
6061 if (j == (
int)fileDescriptorSet[0])
6071 private static void MicrosecondsToTimeValue(
long microSeconds, ref TimeValue socketTime)
6073 socketTime.Seconds = (int)(microSeconds / 1000000);
6074 socketTime.Microseconds = (int)(microSeconds % 1000000);
6077 private IAsyncResult BeginConnectEx(EndPoint remoteEP,
bool flowContext,
AsyncCallback callback,
object state)
6079 if (s_LoggingEnabled)
6081 Logging.Enter(Logging.Sockets,
this,
"BeginConnectEx",
"");
6083 EndPoint remoteEP2 = remoteEP;
6084 SocketAddress socketAddress = flowContext ? CheckCacheRemote(ref remoteEP2, isOverwrite:
true) : SnapshotAndSerialize(ref remoteEP2);
6085 if (m_RightEndPoint ==
null)
6089 InternalBind(
new IPEndPoint(IPAddress.Any, 0));
6093 InternalBind(
new IPEndPoint(IPAddress.IPv6Any, 0));
6096 ConnectOverlappedAsyncResult connectOverlappedAsyncResult =
new ConnectOverlappedAsyncResult(
this, remoteEP2, state, callback);
6099 connectOverlappedAsyncResult.StartPostingAsyncOp(lockCapture:
false);
6101 connectOverlappedAsyncResult.SetUnmanagedStructures(socketAddress.m_Buffer);
6102 EndPoint rightEndPoint = m_RightEndPoint;
6103 if (m_RightEndPoint ==
null)
6105 m_RightEndPoint = remoteEP2;
6117 connectOverlappedAsyncResult.InternalCleanup();
6118 m_RightEndPoint = rightEndPoint;
6125 socketError = connectOverlappedAsyncResult.CheckAsyncCallOverlappedResult(socketError);
6126 if (socketError != 0)
6128 m_RightEndPoint = rightEndPoint;
6129 SocketException ex =
new SocketException(socketError);
6130 UpdateStatusAfterSocketError(ex);
6131 if (s_LoggingEnabled)
6133 Logging.Exception(Logging.Sockets,
this,
"BeginConnectEx", ex);
6137 connectOverlappedAsyncResult.FinishPostingAsyncOp(ref Caches.ConnectClosureCache);
6138 if (s_LoggingEnabled)
6140 Logging.Exit(Logging.Sockets,
this,
"BeginConnectEx", connectOverlappedAsyncResult);
6142 return connectOverlappedAsyncResult;
6145 internal void MultipleSend(BufferOffsetSize[] buffers,
SocketFlags socketFlags)
6147 if (s_LoggingEnabled)
6149 Logging.Enter(Logging.Sockets,
this,
"MultipleSend",
"");
6153 throw new ObjectDisposedException(GetType().FullName);
6155 WSABuffer[] array =
new WSABuffer[buffers.Length];
6160 array2 =
new GCHandle[buffers.Length];
6161 for (
int i = 0; i < buffers.Length; i++)
6164 array[i].Length = buffers[i].Size;
6167 socketError = UnsafeNclNativeMethods.OSSOCK.WSASend_Blocking(m_Handle.DangerousGetHandle(), array, array.Length, out
int _, socketFlags, SafeNativeOverlapped.Zero, IntPtr.Zero);
6173 for (
int j = 0; j < array2.Length; j++)
6175 if (array2[j].IsAllocated)
6182 if (socketError != 0)
6184 SocketException ex =
new SocketException();
6185 UpdateStatusAfterSocketError(ex);
6186 if (s_LoggingEnabled)
6188 Logging.Exception(Logging.Sockets,
this,
"MultipleSend", ex);
6192 if (s_LoggingEnabled)
6194 Logging.Exit(Logging.Sockets,
this,
"MultipleSend",
"");
6198 private static void DnsCallback(IAsyncResult result)
6200 if (!result.CompletedSynchronously)
6203 MultipleAddressConnectAsyncResult multipleAddressConnectAsyncResult = (MultipleAddressConnectAsyncResult)result.AsyncState;
6206 flag = DoDnsCallback(result, multipleAddressConnectAsyncResult);
6208 catch (Exception result2)
6210 multipleAddressConnectAsyncResult.InvokeCallback(result2);
6214 multipleAddressConnectAsyncResult.InvokeCallback();
6219 private static bool DoDnsCallback(IAsyncResult result, MultipleAddressConnectAsyncResult context)
6221 IPAddress[] array = context.addresses =
Dns.EndGetHostAddresses(result);
6222 return DoMultipleAddressConnectCallback(PostOneBeginConnect(context), context);
6225 private static object PostOneBeginConnect(MultipleAddressConnectAsyncResult context)
6227 IPAddress iPAddress = context.addresses[context.index];
6228 if (!context.socket.CanTryAddressFamily(iPAddress.AddressFamily))
6230 if (context.lastException ==
null)
6232 return new ArgumentException(SR.GetString(
"net_invalidAddressList"),
"context");
6234 return context.lastException;
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)
6246 catch (Exception ex)
6257 private static void MultipleAddressConnectCallback(IAsyncResult result)
6259 if (!result.CompletedSynchronously)
6262 MultipleAddressConnectAsyncResult multipleAddressConnectAsyncResult = (MultipleAddressConnectAsyncResult)result.AsyncState;
6265 flag = DoMultipleAddressConnectCallback(result, multipleAddressConnectAsyncResult);
6267 catch (Exception result2)
6269 multipleAddressConnectAsyncResult.InvokeCallback(result2);
6273 multipleAddressConnectAsyncResult.InvokeCallback();
6278 private static bool DoMultipleAddressConnectCallback(
object result, MultipleAddressConnectAsyncResult context)
6280 while (result !=
null)
6282 Exception ex = result as Exception;
6287 context.socket.EndConnect((IAsyncResult)result);
6289 catch (Exception ex2)
6298 if (++context.index >= context.addresses.Length)
6302 context.lastException = ex;
6303 result = PostOneBeginConnect(context);
6308 internal IAsyncResult BeginMultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags, AsyncCallback callback,
object state)
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;
6317 internal IAsyncResult UnsafeBeginMultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags, AsyncCallback callback,
object state)
6319 OverlappedAsyncResult overlappedAsyncResult =
new OverlappedAsyncResult(
this, state, callback);
6320 DoBeginMultipleSend(buffers, socketFlags, overlappedAsyncResult);
6321 return overlappedAsyncResult;
6324 private void DoBeginMultipleSend(BufferOffsetSize[] buffers, SocketFlags socketFlags, OverlappedAsyncResult asyncResult)
6326 if (s_LoggingEnabled)
6328 Logging.Enter(Logging.Sockets,
this,
"BeginMultipleSend",
"");
6332 throw new ObjectDisposedException(GetType().FullName);
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)
6346 socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
6348 if (socketError != 0)
6350 asyncResult.ExtractCache(ref Caches.SendOverlappedCache);
6351 SocketException ex =
new SocketException(socketError);
6352 UpdateStatusAfterSocketError(ex);
6353 if (s_LoggingEnabled)
6355 Logging.Exception(Logging.Sockets,
this,
"BeginMultipleSend", ex);
6359 if (s_LoggingEnabled)
6361 Logging.Exit(Logging.Sockets,
this,
"BeginMultipleSend", asyncResult);
6365 internal int EndMultipleSend(IAsyncResult asyncResult)
6367 if (s_LoggingEnabled)
6369 Logging.Enter(Logging.Sockets,
this,
"EndMultipleSend", asyncResult);
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)
6377 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesSent, num);
6380 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsSent);
6383 if (overlappedAsyncResult.ErrorCode != 0)
6385 SocketException ex =
new SocketException(overlappedAsyncResult.ErrorCode);
6386 if (s_LoggingEnabled)
6388 Logging.Exception(Logging.Sockets,
this,
"EndMultipleSend", ex);
6392 if (s_LoggingEnabled)
6394 Logging.Exit(Logging.Sockets,
this,
"EndMultipleSend", num);
6399 private Socket CreateAcceptSocket(SafeCloseSocket fd, EndPoint remoteEP,
bool needCancelSelect)
6402 return UpdateAcceptSocket(socket, remoteEP, needCancelSelect);
6405 internal Socket UpdateAcceptSocket(Socket socket, EndPoint remoteEP,
bool needCancelSelect)
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)
6416 socket.UnsetAsyncEventSelect();
6420 socket.InternalSetBlocking(willBlock);
6425 internal void SetToConnected()
6429 m_IsConnected =
true;
6430 m_IsDisconnected =
false;
6431 if (s_PerfCountersEnabled)
6433 NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketConnectionsEstablished);
6438 internal void SetToDisconnected()
6442 m_IsConnected =
false;
6443 m_IsDisconnected =
true;
6446 UnsetAsyncEventSelect();
6451 internal void UpdateStatusAfterSocketError(SocketException socketException)
6453 UpdateStatusAfterSocketError((SocketError)socketException.NativeErrorCode);
6456 internal void UpdateStatusAfterSocketError(SocketError errorCode)
6458 if (s_LoggingEnabled)
6460 Logging.PrintError(Logging.Sockets,
this,
"UpdateStatusAfterSocketError", errorCode.ToString());
6464 SetToDisconnected();
6468 private void UnsetAsyncEventSelect()
6471 if (registeredWait !=
null)
6473 m_RegisteredWait =
null;
6479 socketError = UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(m_Handle, IntPtr.Zero, AsyncEventBits.FdNone);
6481 catch (Exception exception)
6483 if (NclUtilities.IsFatal(exception))
6488 if (m_AsyncEvent !=
null)
6492 m_AsyncEvent.
Reset();
6494 catch (ObjectDisposedException)
6500 UpdateStatusAfterSocketError(socketError);
6502 InternalSetBlocking(willBlock);
6505 private bool SetAsyncEventSelect(AsyncEventBits blockEventBits)
6507 if (m_RegisteredWait !=
null)
6511 if (m_AsyncEvent ==
null)
6514 if (s_RegisteredWaitCallback ==
null)
6516 s_RegisteredWaitCallback = RegisteredWaitCallback;
6525 m_BlockEventBits = blockEventBits;
6535 socketError = UnsafeNclNativeMethods.OSSOCK.WSAEventSelect(m_Handle, m_AsyncEvent.SafeWaitHandle, blockEventBits);
6537 catch (Exception exception)
6539 if (NclUtilities.IsFatal(exception))
6546 UpdateStatusAfterSocketError(socketError);
6548 willBlockInternal =
false;
6552 private static void RegisteredWaitCallback(
object state,
bool timedOut)
6557 switch (socket.m_BlockEventBits)
6559 case AsyncEventBits.FdConnect:
6560 socket.ConnectCallback();
6562 case AsyncEventBits.FdAccept:
6563 socket.AcceptCallback(
null);
6569 private void ValidateBlockingMode()
6571 if (willBlock && !willBlockInternal)
6573 throw new InvalidOperationException(SR.GetString(
"net_invasync"));
6578 internal void BindToCompletionPort()
6580 if (!m_BoundToThreadPool && !UseOverlappedIO)
6584 if (!m_BoundToThreadPool)
6589 m_BoundToThreadPool =
true;
6591 catch (Exception exception)
6593 if (NclUtilities.IsFatal(exception))
6616 if (s_LoggingEnabled)
6618 Logging.Enter(Logging.Sockets,
this,
"AcceptAsync",
"");
6624 if (e.m_BufferList !=
null)
6626 throw new ArgumentException(SR.GetString(
"net_multibuffernotsupported"),
"BufferList");
6628 if (m_RightEndPoint ==
null)
6644 e.StartOperationCommon(
this);
6645 e.StartOperationAccept();
6646 BindToCompletionPort();
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))
6662 if (socketError != 0 && socketError !=
SocketError.IOPending)
6664 e.FinishOperationSyncFailure(socketError, bytesReceived,
SocketFlags.None);
6671 if (s_LoggingEnabled)
6673 Logging.Exit(Logging.Sockets,
this,
"AcceptAsync", flag);
6690 if (s_LoggingEnabled)
6692 Logging.Enter(Logging.Sockets,
this,
"ConnectAsync",
"");
6698 if (e.m_BufferList !=
null)
6700 throw new ArgumentException(SR.GetString(
"net_multibuffernotsupported"),
"BufferList");
6713 if (dnsEndPoint !=
null)
6715 if (s_LoggingEnabled)
6717 Logging.PrintInfo(Logging.Sockets,
"Socket#" + ValidationHelper.HashString(
this) +
"::ConnectAsync " + SR.GetString(
"net_log_socket_connect_dnsendpoint"));
6723 MultipleConnectAsync multipleConnectAsync =
new SingleSocketMultipleConnectAsync(
this, userSocket:
true);
6724 e.StartOperationCommon(
this);
6725 e.StartOperationWrapperConnect(multipleConnectAsync);
6726 flag = multipleConnectAsync.StartConnectAsync(e, dnsEndPoint);
6734 e.m_SocketAddress = CheckCacheRemote(ref remoteEP, isOverwrite:
false);
6735 if (m_RightEndPoint ==
null)
6746 EndPoint rightEndPoint = m_RightEndPoint;
6747 if (m_RightEndPoint ==
null)
6749 m_RightEndPoint = remoteEP;
6751 e.StartOperationCommon(
this);
6752 e.StartOperationConnect();
6753 BindToCompletionPort();
6758 if (!ConnectEx(m_Handle, e.m_PtrSocketAddressBuffer, e.m_SocketAddress.m_Size, e.m_PtrSingleBuffer, e.
Count, out bytesSent, e.m_PtrNativeOverlapped))
6765 m_RightEndPoint = rightEndPoint;
6769 if (socketError != 0 && socketError !=
SocketError.IOPending)
6771 e.FinishOperationSyncFailure(socketError, bytesSent,
SocketFlags.None);
6779 if (s_LoggingEnabled)
6781 Logging.Exit(Logging.Sockets,
this,
"ConnectAsync", flag);
6800 if (s_LoggingEnabled)
6802 Logging.Enter(Logging.Sockets,
null,
"ConnectAsync",
"");
6804 if (e.m_BufferList !=
null)
6806 throw new ArgumentException(SR.GetString(
"net_multibuffernotsupported"),
"BufferList");
6815 if (dnsEndPoint !=
null)
6818 MultipleConnectAsync multipleConnectAsync =
null;
6821 multipleConnectAsync =
new MultipleSocketMultipleConnectAsync(socketType, protocolType);
6826 multipleConnectAsync =
new SingleSocketMultipleConnectAsync(socket, userSocket:
false);
6828 e.StartOperationCommon(socket);
6829 e.StartOperationWrapperConnect(multipleConnectAsync);
6830 flag = multipleConnectAsync.StartConnectAsync(e, dnsEndPoint);
6837 if (s_LoggingEnabled)
6839 Logging.Exit(Logging.Sockets,
null,
"ConnectAsync", flag);
6856 e.CancelConnectAsync();
6869 if (s_LoggingEnabled)
6871 Logging.Enter(Logging.Sockets,
this,
"DisconnectAsync",
"");
6877 e.StartOperationCommon(
this);
6878 e.StartOperationDisconnect();
6879 BindToCompletionPort();
6894 if (socketError != 0 && socketError !=
SocketError.IOPending)
6896 e.FinishOperationSyncFailure(socketError, 0,
SocketFlags.None);
6903 if (s_LoggingEnabled)
6905 Logging.Exit(Logging.Sockets,
this,
"DisconnectAsync", flag);
6920 if (s_LoggingEnabled)
6922 Logging.Enter(Logging.Sockets,
this,
"ReceiveAsync",
"");
6928 e.StartOperationCommon(
this);
6929 e.StartOperationReceive();
6930 BindToCompletionPort();
6933 int bytesTransferred;
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));
6943 if (socketError != 0)
6948 if (socketError != 0 && socketError !=
SocketError.IOPending)
6950 e.FinishOperationSyncFailure(socketError, bytesTransferred, socketFlags);
6957 if (s_LoggingEnabled)
6959 Logging.Exit(Logging.Sockets,
this,
"ReceiveAsync", flag);
6974 if (s_LoggingEnabled)
6976 Logging.Enter(Logging.Sockets,
this,
"ReceiveFromAsync",
"");
6991 e.m_SocketAddress = SnapshotAndSerialize(ref remoteEP);
6993 e.StartOperationCommon(
this);
6994 e.StartOperationReceiveFrom();
6995 BindToCompletionPort();
6998 int bytesTransferred;
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));
7008 if (socketError != 0)
7013 if (socketError != 0 && socketError !=
SocketError.IOPending)
7015 e.FinishOperationSyncFailure(socketError, bytesTransferred, socketFlags);
7022 if (s_LoggingEnabled)
7024 Logging.Exit(Logging.Sockets,
this,
"ReceiveFromAsync", flag);
7038 if (s_LoggingEnabled)
7040 Logging.Enter(Logging.Sockets,
this,
"ReceiveMessageFromAsync",
"");
7055 e.m_SocketAddress = SnapshotAndSerialize(ref remoteEP);
7057 SetReceivingPacketInformation();
7058 e.StartOperationCommon(
this);
7059 e.StartOperationReceiveMessageFrom();
7060 BindToCompletionPort();
7062 int bytesTransferred;
7065 socketError = WSARecvMsg(m_Handle, e.m_PtrWSAMessageBuffer, out bytesTransferred, e.m_PtrNativeOverlapped,
IntPtr.
Zero);
7072 if (socketError != 0)
7077 if (socketError != 0 && socketError !=
SocketError.IOPending)
7079 e.FinishOperationSyncFailure(socketError, bytesTransferred,
SocketFlags.None);
7086 if (s_LoggingEnabled)
7088 Logging.Exit(Logging.Sockets,
this,
"ReceiveMessageFromAsync", flag);
7103 if (s_LoggingEnabled)
7105 Logging.Enter(Logging.Sockets,
this,
"SendAsync",
"");
7111 e.StartOperationCommon(
this);
7112 e.StartOperationSend();
7113 BindToCompletionPort();
7115 int bytesTransferred;
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));
7125 if (socketError != 0)
7130 if (socketError != 0 && socketError !=
SocketError.IOPending)
7132 e.FinishOperationSyncFailure(socketError, bytesTransferred,
SocketFlags.None);
7139 if (s_LoggingEnabled)
7141 Logging.Enter(Logging.Sockets,
this,
"SendAsync", flag);
7156 if (s_LoggingEnabled)
7158 Logging.Enter(Logging.Sockets,
this,
"SendPacketsAsync",
"");
7168 e.StartOperationCommon(
this);
7169 e.StartOperationSendPackets();
7170 BindToCompletionPort();
7172 if (e.m_SendPacketsDescriptor.Length != 0)
7177 flag = TransmitPackets(m_Handle, e.m_PtrSendPacketsDescriptor, e.m_SendPacketsDescriptor.Length, e.m_SendPacketsSendSize, e.m_PtrNativeOverlapped, e.m_SendPacketsFlags);
7185 if (socketError != 0 && socketError !=
SocketError.IOPending)
7187 e.FinishOperationSyncFailure(socketError, 0,
SocketFlags.None);
7200 if (s_LoggingEnabled)
7202 Logging.Exit(Logging.Sockets,
this,
"SendPacketsAsync", flag2);
7217 if (s_LoggingEnabled)
7219 Logging.Enter(Logging.Sockets,
this,
"SendToAsync",
"");
7230 e.m_SocketAddress = CheckCacheRemote(ref remoteEP, isOverwrite:
false);
7231 e.StartOperationCommon(
this);
7232 e.StartOperationSendTo();
7233 BindToCompletionPort();
7235 int bytesTransferred;
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));
7245 if (socketError != 0)
7250 if (socketError != 0 && socketError !=
SocketError.IOPending)
7252 e.FinishOperationSyncFailure(socketError, bytesTransferred,
SocketFlags.None);
7259 if (s_LoggingEnabled)
7261 Logging.Exit(Logging.Sockets,
this,
"SendToAsync", flag);
7268 TaskSocketAsyncEventArgs<Socket> taskSocketAsyncEventArgs =
Interlocked.
Exchange(ref
LazyInitializer.EnsureInitialized(ref _cachedTaskEventArgs).Accept, s_rentedSocketSentinel);
7269 if (taskSocketAsyncEventArgs == s_rentedSocketSentinel)
7271 return AcceptAsyncApm(acceptSocket);
7273 if (taskSocketAsyncEventArgs ==
null)
7275 taskSocketAsyncEventArgs =
new TaskSocketAsyncEventArgs<Socket>();
7276 taskSocketAsyncEventArgs.Completed += AcceptCompletedHandler;
7278 taskSocketAsyncEventArgs.AcceptSocket = acceptSocket;
7280 if (AcceptAsync(taskSocketAsyncEventArgs))
7282 result = taskSocketAsyncEventArgs.GetCompletionResponsibility(out
bool responsibleForReturningToPool).Task;
7283 if (responsibleForReturningToPool)
7285 ReturnSocketAsyncEventArgs(taskSocketAsyncEventArgs);
7290 result = ((taskSocketAsyncEventArgs.SocketError ==
SocketError.Success) ?
Task.FromResult(taskSocketAsyncEventArgs.AcceptSocket) :
Task.
FromException<
Socket>(GetException(taskSocketAsyncEventArgs.SocketError)));
7291 ReturnSocketAsyncEventArgs(taskSocketAsyncEventArgs);
7296 private Task<Socket> AcceptAsyncApm(Socket acceptSocket)
7299 BeginAccept(acceptSocket, 0, delegate(IAsyncResult iar)
7304 taskCompletionSource2.
TrySetResult(((Socket)taskCompletionSource2.
Task.AsyncState).EndAccept(iar));
7306 catch (Exception exception)
7308 taskCompletionSource2.TrySetException(exception);
7310 }, taskCompletionSource);
7311 return taskCompletionSource.
Task;
7314 internal Task ConnectAsync(EndPoint remoteEP)
7317 BeginConnect(remoteEP, delegate(IAsyncResult iar)
7322 ((Socket)taskCompletionSource2.
Task.AsyncState).EndConnect(iar);
7325 catch (Exception exception)
7329 }, taskCompletionSource);
7330 return taskCompletionSource.
Task;
7333 internal Task ConnectAsync(IPAddress address,
int port)
7336 BeginConnect(address, port, delegate(IAsyncResult iar)
7341 ((Socket)taskCompletionSource2.
Task.AsyncState).EndConnect(iar);
7344 catch (Exception exception)
7348 }, taskCompletionSource);
7349 return taskCompletionSource.
Task;
7352 internal Task ConnectAsync(IPAddress[] addresses,
int port)
7355 BeginConnect(addresses, port, delegate(IAsyncResult iar)
7360 ((Socket)taskCompletionSource2.
Task.AsyncState).EndConnect(iar);
7363 catch (Exception exception)
7367 }, taskCompletionSource);
7368 return taskCompletionSource.
Task;
7371 internal Task ConnectAsync(
string host,
int port)
7374 BeginConnect(host, port, delegate(IAsyncResult iar)
7379 ((Socket)taskCompletionSource2.
Task.AsyncState).EndConnect(iar);
7382 catch (Exception exception)
7386 }, taskCompletionSource);
7387 return taskCompletionSource.
Task;
7390 internal Task<int> ReceiveAsync(ArraySegment<byte> buffer, SocketFlags socketFlags,
bool fromNetworkStream)
7392 ValidateBuffer(buffer);
7393 Int32TaskSocketAsyncEventArgs int32TaskSocketAsyncEventArgs = RentSocketAsyncEventArgs(isReceive:
true);
7394 if (int32TaskSocketAsyncEventArgs !=
null)
7396 ConfigureBuffer(int32TaskSocketAsyncEventArgs, buffer, socketFlags, fromNetworkStream);
7397 return GetTaskForSendReceive(ReceiveAsync(int32TaskSocketAsyncEventArgs), int32TaskSocketAsyncEventArgs, fromNetworkStream, isReceive:
true);
7399 return ReceiveAsyncApm(buffer, socketFlags);
7402 private Task<int> ReceiveAsyncApm(ArraySegment<byte> buffer, SocketFlags socketFlags)
7405 BeginReceive(buffer.Array, buffer.Offset, buffer.Count, socketFlags, delegate(IAsyncResult iar)
7410 taskCompletionSource2.
TrySetResult(((Socket)taskCompletionSource2.
Task.AsyncState).EndReceive(iar));
7412 catch (Exception exception)
7416 }, taskCompletionSource);
7417 return taskCompletionSource.
Task;
7420 internal Task<int> ReceiveAsync(
IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
7422 ValidateBuffersList(buffers);
7423 Int32TaskSocketAsyncEventArgs int32TaskSocketAsyncEventArgs = RentSocketAsyncEventArgs(isReceive:
true);
7424 if (int32TaskSocketAsyncEventArgs !=
null)
7426 ConfigureBufferList(int32TaskSocketAsyncEventArgs, buffers, socketFlags);
7427 return GetTaskForSendReceive(ReceiveAsync(int32TaskSocketAsyncEventArgs), int32TaskSocketAsyncEventArgs, fromNetworkStream:
false, isReceive:
true);
7429 return ReceiveAsyncApm(buffers, socketFlags);
7432 private Task<int> ReceiveAsyncApm(
IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
7435 BeginReceive(buffers, socketFlags, delegate(IAsyncResult iar)
7440 taskCompletionSource2.
TrySetResult(((Socket)taskCompletionSource2.
Task.AsyncState).EndReceive(iar));
7442 catch (Exception exception)
7446 }, taskCompletionSource);
7447 return taskCompletionSource.
Task;
7452 StateTaskCompletionSource<EndPoint, SocketReceiveFromResult> stateTaskCompletionSource =
new StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>(
this)
7454 _field1 = remoteEndPoint
7456 BeginReceiveFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref stateTaskCompletionSource._field1, delegate(IAsyncResult iar)
7458 StateTaskCompletionSource<EndPoint, SocketReceiveFromResult> stateTaskCompletionSource2 = (StateTaskCompletionSource<EndPoint, SocketReceiveFromResult>)iar.AsyncState;
7461 int receivedBytes = ((Socket)stateTaskCompletionSource2.Task.AsyncState).EndReceiveFrom(iar, ref stateTaskCompletionSource2._field1);
7462 stateTaskCompletionSource2.TrySetResult(
new SocketReceiveFromResult
7464 ReceivedBytes = receivedBytes,
7465 RemoteEndPoint = stateTaskCompletionSource2._field1
7468 catch (Exception exception)
7470 stateTaskCompletionSource2.TrySetException(exception);
7472 }, stateTaskCompletionSource);
7473 return stateTaskCompletionSource.Task;
7478 StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult> stateTaskCompletionSource =
new StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>(
this)
7480 _field1 = socketFlags,
7481 _field2 = remoteEndPoint
7483 BeginReceiveMessageFrom(buffer.Array, buffer.Offset, buffer.Count, socketFlags, ref stateTaskCompletionSource._field2, delegate(IAsyncResult iar)
7485 StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult> stateTaskCompletionSource2 = (StateTaskCompletionSource<SocketFlags, EndPoint, SocketReceiveMessageFromResult>)iar.AsyncState;
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
7492 ReceivedBytes = receivedBytes,
7493 RemoteEndPoint = stateTaskCompletionSource2._field2,
7498 catch (Exception exception)
7500 stateTaskCompletionSource2.TrySetException(exception);
7502 }, stateTaskCompletionSource);
7503 return stateTaskCompletionSource.Task;
7506 internal Task<int> SendAsync(ArraySegment<byte> buffer, SocketFlags socketFlags,
bool fromNetworkStream)
7508 ValidateBuffer(buffer);
7509 Int32TaskSocketAsyncEventArgs int32TaskSocketAsyncEventArgs = RentSocketAsyncEventArgs(isReceive:
false);
7510 if (int32TaskSocketAsyncEventArgs !=
null)
7512 ConfigureBuffer(int32TaskSocketAsyncEventArgs, buffer, socketFlags, fromNetworkStream);
7513 return GetTaskForSendReceive(SendAsync(int32TaskSocketAsyncEventArgs), int32TaskSocketAsyncEventArgs, fromNetworkStream, isReceive:
false);
7515 return SendAsyncApm(buffer, socketFlags);
7518 private Task<int> SendAsyncApm(ArraySegment<byte> buffer, SocketFlags socketFlags)
7521 BeginSend(buffer.Array, buffer.Offset, buffer.Count, socketFlags, delegate(IAsyncResult iar)
7526 taskCompletionSource2.
TrySetResult(((Socket)taskCompletionSource2.
Task.AsyncState).EndSend(iar));
7528 catch (Exception exception)
7532 }, taskCompletionSource);
7533 return taskCompletionSource.
Task;
7536 internal Task<int> SendAsync(
IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
7538 ValidateBuffersList(buffers);
7539 Int32TaskSocketAsyncEventArgs int32TaskSocketAsyncEventArgs = RentSocketAsyncEventArgs(isReceive:
false);
7540 if (int32TaskSocketAsyncEventArgs !=
null)
7542 ConfigureBufferList(int32TaskSocketAsyncEventArgs, buffers, socketFlags);
7543 return GetTaskForSendReceive(SendAsync(int32TaskSocketAsyncEventArgs), int32TaskSocketAsyncEventArgs, fromNetworkStream:
false, isReceive:
false);
7545 return SendAsyncApm(buffers, socketFlags);
7548 private Task<int> SendAsyncApm(
IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
7551 BeginSend(buffers, socketFlags, delegate(IAsyncResult iar)
7556 taskCompletionSource2.
TrySetResult(((Socket)taskCompletionSource2.
Task.AsyncState).EndSend(iar));
7558 catch (Exception exception)
7562 }, taskCompletionSource);
7563 return taskCompletionSource.
Task;
7566 internal Task<int> SendToAsync(ArraySegment<byte> buffer, SocketFlags socketFlags, EndPoint remoteEP)
7569 BeginSendTo(buffer.Array, buffer.Offset, buffer.Count, socketFlags, remoteEP, delegate(IAsyncResult iar)
7574 taskCompletionSource2.
TrySetResult(((Socket)taskCompletionSource2.
Task.AsyncState).EndSendTo(iar));
7576 catch (Exception exception)
7580 }, taskCompletionSource);
7581 return taskCompletionSource.
Task;
7584 private static void ValidateBuffer(ArraySegment<byte> buffer)
7586 if (buffer.Array ==
null)
7588 throw new ArgumentNullException(
"Array");
7590 if (buffer.Offset < 0 || buffer.Offset > buffer.Array.Length)
7592 throw new ArgumentOutOfRangeException(
"Offset");
7594 if (buffer.Count < 0 || buffer.Count > buffer.Array.Length - buffer.Offset)
7596 throw new ArgumentOutOfRangeException(
"Count");
7600 private static void ValidateBuffersList(
IList<ArraySegment<byte>> buffers)
7602 if (buffers ==
null)
7604 throw new ArgumentNullException(
"buffers");
7606 if (buffers.Count == 0)
7608 throw new ArgumentException(
string.Format(
"net_sockets_zerolist",
"buffers"),
"buffers");
7612 private static void ConfigureBuffer(Int32TaskSocketAsyncEventArgs saea, ArraySegment<byte> buffer, SocketFlags socketFlags,
bool wrapExceptionsInIOExceptions)
7614 if (saea.BufferList !=
null)
7616 saea.BufferList =
null;
7618 saea.SetBuffer(buffer.Array, buffer.Offset, buffer.Count);
7619 saea.SocketFlags = socketFlags;
7620 saea._wrapExceptionsInIOExceptions = wrapExceptionsInIOExceptions;
7623 private static void ConfigureBufferList(Int32TaskSocketAsyncEventArgs saea,
IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
7625 if (saea.Buffer !=
null)
7627 saea.SetBuffer(
null, 0, 0);
7629 saea.BufferList = buffers;
7630 saea.SocketFlags = socketFlags;
7633 private Task<int> GetTaskForSendReceive(
bool pending, Int32TaskSocketAsyncEventArgs saea,
bool fromNetworkStream,
bool isReceive)
7638 result = saea.GetCompletionResponsibility(out
bool responsibleForReturningToPool).Task;
7639 if (responsibleForReturningToPool)
7641 ReturnSocketAsyncEventArgs(saea, isReceive);
7648 int bytesTransferred = saea.BytesTransferred;
7649 if (bytesTransferred == 0 || (fromNetworkStream && !isReceive))
7651 result = s_zeroTask;
7655 Task<int> successfullyCompletedTask = saea._successfullyCompletedTask;
7656 result = ((successfullyCompletedTask !=
null && successfullyCompletedTask.
Result == bytesTransferred) ? successfullyCompletedTask : (saea._successfullyCompletedTask =
Task.FromResult(bytesTransferred)));
7661 result =
Task.
FromException<
int>(GetException(saea.SocketError, fromNetworkStream));
7663 ReturnSocketAsyncEventArgs(saea, isReceive);
7668 private static void CompleteAccept(Socket s, TaskSocketAsyncEventArgs<Socket> saea)
7671 Socket acceptSocket = saea.AcceptSocket;
7672 bool responsibleForReturningToPool;
7674 if (responsibleForReturningToPool)
7676 s.ReturnSocketAsyncEventArgs(saea);
7680 completionResponsibility.SetResult(acceptSocket);
7684 completionResponsibility.SetException(GetException(socketError));
7688 private static void CompleteSendReceive(Socket s, Int32TaskSocketAsyncEventArgs saea,
bool isReceive)
7691 int bytesTransferred = saea.BytesTransferred;
7692 bool wrapExceptionsInIOExceptions = saea._wrapExceptionsInIOExceptions;
7693 bool responsibleForReturningToPool;
7695 if (responsibleForReturningToPool)
7697 s.ReturnSocketAsyncEventArgs(saea, isReceive);
7701 completionResponsibility.SetResult(bytesTransferred);
7705 completionResponsibility.SetException(GetException(socketError, wrapExceptionsInIOExceptions));
7709 private static Exception GetException(SocketError error,
bool wrapExceptionsInIOExceptions =
false)
7711 Exception ex =
new SocketException((
int)error);
7712 if (!wrapExceptionsInIOExceptions)
7716 return new IOException(
string.Format(
"net_io_readwritefailure", ex.Message), ex);
7719 private Int32TaskSocketAsyncEventArgs RentSocketAsyncEventArgs(
bool isReceive)
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)
7727 if (int32TaskSocketAsyncEventArgs ==
null)
7729 int32TaskSocketAsyncEventArgs =
new Int32TaskSocketAsyncEventArgs();
7730 int32TaskSocketAsyncEventArgs.Completed += (isReceive ? ReceiveCompletedHandler : SendCompletedHandler);
7732 return int32TaskSocketAsyncEventArgs;
7735 private void ReturnSocketAsyncEventArgs(Int32TaskSocketAsyncEventArgs saea,
bool isReceive)
7737 saea._accessed =
false;
7739 saea._wrapExceptionsInIOExceptions =
false;
7750 private void ReturnSocketAsyncEventArgs(TaskSocketAsyncEventArgs<Socket> saea)
7752 saea.AcceptSocket =
null;
7753 saea._accessed =
false;
7758 private void DisposeCachedTaskSocketAsyncEventArgs()
7760 CachedTaskEventArgs cachedTaskEventArgs = _cachedTaskEventArgs;
7761 if (cachedTaskEventArgs !=
null)
static Thread CurrentThread
Gets the currently running thread.
bool IsThreadPoolThread
Gets a value indicating whether or not a thread belongs to the managed thread pool.
virtual EndPoint Create(SocketAddress socketAddress)
Creates an T:System.Net.EndPoint instance from a T:System.Net.SocketAddress instance.
Socket EndAccept(out byte[] buffer, out int bytesTransferred, IAsyncResult asyncResult)
Asynchronously accepts an incoming connection attempt and creates a new T:System.Net....
void Close(int timeout)
Closes the T:System.Net.Sockets.Socket connection and releases all associated resources with a specif...
bool Connected
Gets a value that indicates whether a T:System.Net.Sockets.Socket is connected to a remote host as of...
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....
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....
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.
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...
object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName)
Returns the value of a specified T:System.Net.Sockets.Socket option, represented as an object.
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...
void Listen(int backlog)
Places a T:System.Net.Sockets.Socket in a listening state.
SocketOptionName
Defines configuration option names.
int ReceiveTimeout
Gets or sets a value that specifies the amount of time after which a synchronous Overload:System....
EndPoint RemoteEndPoint
Gets the remote endpoint.
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.
int EndSend(IAsyncResult asyncResult)
Ends a pending asynchronous send.
TResult Result
Gets the result value of this T:System.Threading.Tasks.Task`1.
virtual void Dispose(bool disposing)
Releases the unmanaged resources used by the T:System.Net.Sockets.Socket, and optionally disposes of ...
SafeWaitHandle SafeWaitHandle
Gets or sets the native operating system handle.
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,...
static void SuppressFinalize(object obj)
Requests that the common language runtime not call the finalizer for the specified object.
void SendFile(string fileName)
Sends the file fileName to a connected T:System.Net.Sockets.Socket object with the F:System....
NetworkAccess
Specifies network access permissions.
IntPtr Handle
Gets the operating system handle for the T:System.Net.Sockets.Socket.
bool ReceiveAsync(SocketAsyncEventArgs e)
Begins an asynchronous request to receive data from a connected T:System.Net.Sockets....
FileMode
Specifies how the operating system should open a file.
Represents a non-generic collection of objects that can be individually accessed by index.
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....
bool AcceptAsync(SocketAsyncEventArgs e)
Begins an asynchronous operation to accept an incoming connection attempt.
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.
Provides a mechanism for releasing unmanaged resources.To browse the .NET Framework source code for t...
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 ...
static readonly IPAddress Any
Provides an IP address that indicates that the server must listen for client activity on all network ...
int IOControl(int ioControlCode, byte[] optionInValue, byte[] optionOutValue)
Sets low-level operating modes for the T:System.Net.Sockets.Socket using numerical control codes.
bool Poll(int microSeconds, SelectMode mode)
Determines the status of the T:System.Net.Sockets.Socket.
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,...
Address for IP version 6.
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.
void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
Sets the specified T:System.Net.Sockets.Socket option to the specified T:System.Boolean value.
IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state)
Sends data asynchronously to a specific remote host.
IAsyncResult BeginSend(IList< ArraySegment< byte >> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
Sends data asynchronously to a connected T:System.Net.Sockets.Socket.
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.
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.
virtual object Peek()
Returns the object at the beginning of the T:System.Collections.Queue without removing it.
unsafe SocketInformation DuplicateAndClose(int targetProcessId)
Duplicates the socket reference for the target process, and closes the socket for this process.
int Offset
Gets the position of the first element in the range delimited by the array segment,...
static bool SupportsIPv6
Gets a value that indicates whether the Framework supports IPv6 for certain obsolete T:System....
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...
AddressFamily AddressFamily
Gets the address family of the T:System.Net.Sockets.Socket.
int Send(byte[] buffer, SocketFlags socketFlags)
Sends data to a connected T:System.Net.Sockets.Socket using the specified T:System....
virtual void Enqueue(object obj)
Adds an object to the end of the T:System.Collections.Queue.
void EndConnect(IAsyncResult asyncResult)
Ends a pending asynchronous connection request.
bool? NoDelay
Gets or sets a T:System.Boolean value that specifies whether the stream T:System.Net....
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...
Implements the Berkeley sockets interface.
SocketType SocketType
Gets the type of the T:System.Net.Sockets.Socket.
short Ttl
Gets or sets a value that specifies the Time To Live (TTL) value of Internet Protocol (IP) packets se...
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...
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....
unsafe override string ToString()
Converts an Internet address to its standard notation.
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.
int IOControl(IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue)
Sets low-level operating modes for the T:System.Net.Sockets.Socket using the T:System....
IAsyncResult BeginAccept(int receiveSize, AsyncCallback callback, object state)
Begins an asynchronous operation to accept an incoming connection attempt and receives the first bloc...
Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
Initializes a new instance of the T:System.Net.Sockets.Socket class using the specified address famil...
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...
The exception that is thrown when a socket error occurs.
AddressFamily AddressFamily
Gets the address family of the IP address.
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.
void Close()
Closes the T:System.Net.Sockets.Socket connection and releases all associated resources.
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...
static IPAddress [] GetHostAddresses(string hostNameOrAddress)
Returns the Internet Protocol (IP) addresses for the specified host.
The exception that is thrown when an operation is performed on a disposed object.
override AddressFamily AddressFamily
Gets the Internet Protocol (IP) address family.
bool? EnableBroadcast
Gets or sets a T:System.Boolean value that specifies whether the T:System.Net.Sockets....
Provides an Internet Protocol (IP) address.
IOControlCode
Specifies the IO control codes supported by the M:System.Net.Sockets.Socket.IOControl(System....
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.
int SendTimeout
Gets or sets a value that specifies the amount of time after which a synchronous Overload:System....
Represents the status of an asynchronous operation.
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...
SocketType
Specifies the type of socket that an instance of the T:System.Net.Sockets.Socket class represents.
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....
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.
int EndReceive(IAsyncResult asyncResult, out SocketError errorCode)
Ends a pending asynchronous read.
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...
bool?? MulticastLoopback
Gets or sets a value that specifies whether outgoing multicast packets are delivered to the sending a...
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.
Socket EndAccept(IAsyncResult asyncResult)
Asynchronously accepts an incoming connection attempt and creates a new T:System.Net....
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....
Provides lazy initialization routines.
IAsyncResult BeginAccept(AsyncCallback callback, object state)
Begins an asynchronous operation to accept an incoming connection attempt.
static readonly IPAddress IPv6Any
The M:System.Net.Sockets.Socket.Bind(System.Net.EndPoint) method uses the F:System....
Represents a network endpoint as a host name or a string representation of an IP address and a port n...
void EndSendFile(IAsyncResult asyncResult)
Ends a pending asynchronous send of a file.
static void CancelConnectAsync(SocketAsyncEventArgs e)
Cancels an asynchronous request for a remote host connection.
virtual int Count
Gets the number of elements contained in the T:System.Collections.Queue.
AddressFamily
Specifies the addressing scheme that an instance of the T:System.Net.Sockets.Socket class can use.
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.
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...
static bool SupportsIPv4
Gets a value indicating whether IPv4 support is available and enabled on the current host.
Provides a T:System.IO.Stream for a file, supporting both synchronous and asynchronous read and write...
int ReceiveBufferSize
Gets or sets a value that specifies the size of the receive buffer of the T:System....
IPAddress Address
Gets or sets the IP address of the endpoint.
int Port
Gets or sets the port number of the endpoint.
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.
The exception that is thrown when an I/O error occurs.
bool SendToAsync(SocketAsyncEventArgs e)
Sends data asynchronously to a specific remote host.
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.
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 ...
void Bind(EndPoint localEP)
Associates a T:System.Net.Sockets.Socket with a local endpoint.
static bool ConnectAsync(SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
Begins an asynchronous request for a connection to a remote host.
Defines the underlying structure of all code access permissions.
A platform-specific type that is used to represent a pointer or a handle.
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.
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 ...
Provides methods for creating, manipulating, searching, and sorting arrays, thereby serving as the ba...
Represents a network endpoint as an IP address and a port number.
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,...
static GCHandle Alloc(object value)
Allocates a F:System.Runtime.InteropServices.GCHandleType.Normal handle for the specified object.
int Send(IList< ArraySegment< byte >> buffers)
Sends the set of buffers in the list to a connected T:System.Net.Sockets.Socket.
Provides a collection of methods for allocating unmanaged memory, copying unmanaged memory blocks,...
Contains methods for performing volatile memory operations.
Represents a first-in, first-out collection of objects.
GCHandleType
Represents the types of handles the T:System.Runtime.InteropServices.GCHandle class can allocate.
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...
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...
Socket EndAccept(out byte[] buffer, IAsyncResult asyncResult)
Asynchronously accepts an incoming connection attempt and creates a new T:System.Net....
bool? DontFragment
Gets or sets a T:System.Boolean value that specifies whether the T:System.Net.Sockets....
Provides a way to access a managed object from unmanaged memory.
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.
virtual SocketAddress Serialize()
Serializes endpoint information into a T:System.Net.SocketAddress instance.
T [] Array
Gets the original array containing the range of elements that the array segment delimits.
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....
bool CompletedSynchronously
Gets a value that indicates whether the asynchronous operation completed synchronously.
int EndSendTo(IAsyncResult asyncResult)
Ends a pending asynchronous send to a specific location.
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.
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...
virtual void Close()
Releases all resources held by the current T:System.Threading.WaitHandle.
int EndSend(IAsyncResult asyncResult, out SocketError errorCode)
Ends a pending asynchronous send.
int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint)
Ends a pending asynchronous read from a specific endpoint.
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.
int Receive(IList< ArraySegment< byte >> buffers, SocketFlags socketFlags)
Receives data from a bound T:System.Net.Sockets.Socket into the list of receive buffers,...
Exception()
Initializes a new instance of the T:System.Exception class.
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.
SocketFlags
Specifies socket send and receive behaviors.
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 ...
virtual AddressFamily AddressFamily
Gets the address family to which the endpoint belongs.
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....
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 ...
Specifies whether a T:System.Net.Sockets.Socket will remain connected after a call to the M:System....
int Available
Gets the amount of data that has been received from the network and is available to be read.
int Send(byte[] buffer)
Sends data to a connected T:System.Net.Sockets.Socket.
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....
static bool BindHandle(IntPtr osHandle)
Binds an operating system handle to the T:System.Threading.ThreadPool.
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...
void Shutdown(SocketShutdown how)
Disables sends and receives on a T:System.Net.Sockets.Socket.
static void PtrToStructure(IntPtr ptr, object structure)
Marshals data from an unmanaged block of memory to a managed object.
bool ConnectAsync(SocketAsyncEventArgs e)
Begins an asynchronous request for a connection to a remote host.
int Send(byte[] buffer, int size, SocketFlags socketFlags)
Sends the specified number of bytes of data to a connected T:System.Net.Sockets.Socket,...
virtual SafeFileHandle SafeFileHandle
Gets a T:Microsoft.Win32.SafeHandles.SafeFileHandle object that represents the operating system file ...
Represents errors that occur during application execution.To browse the .NET Framework source code fo...
IAsyncResult BeginConnect(EndPoint remoteEP, AsyncCallback callback, object state)
Begins an asynchronous request for a remote host connection.
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.
int ReceiveFrom(byte[] buffer, SocketFlags socketFlags, ref EndPoint remoteEP)
Receives a datagram into the data buffer, using the specified T:System.Net.Sockets....
int LingerTime
Gets or sets the amount of time to remain connected after calling the M:System.Net....
static readonly IntPtr Zero
A read-only field that represents a pointer or handle that has been initialized to zero.
bool Blocking
Gets or sets a value that indicates whether the T:System.Net.Sockets.Socket is in blocking mode.
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.
void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
Returns the specified T:System.Net.Sockets.Socket option setting, represented as a byte array.
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.
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.
void SetIPProtectionLevel(IPProtectionLevel level)
Set the IP protection level on a socket.
Provides simple domain name resolution functionality.
Represents an asynchronous socket operation.
static bool OSSupportsIPv6
Indicates whether the underlying operating system and network adaptors support Internet Protocol vers...
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,...
int EndReceive(IAsyncResult asyncResult)
Ends a pending asynchronous read.
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...
void Connect(EndPoint remoteEP)
Establishes a connection to a remote host.
int ReceiveFrom(byte[] buffer, ref EndPoint remoteEP)
Receives a datagram into the data buffer and stores the endpoint.
bool ReceiveFromAsync(SocketAsyncEventArgs e)
Begins to asynchronously receive data from a specified network device.
int Count
Gets the number of elements contained in the T:System.Collections.ICollection.
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...
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.
int Receive(IList< ArraySegment< byte >> buffers)
Receives data from a bound T:System.Net.Sockets.Socket into the list of receive buffers.
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...
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.
void Disconnect(bool reuseSocket)
Closes the socket connection and allows reuse of the socket.
void EndDisconnect(IAsyncResult asyncResult)
Ends a pending asynchronous disconnect request.
virtual object Dequeue()
Removes and returns the object at the beginning of the T:System.Collections.Queue.
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.
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.
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.
unsafe Socket(SocketInformation socketInformation)
Initializes a new instance of the T:System.Net.Sockets.Socket class using the specified value returne...
Provides atomic operations for variables that are shared by multiple threads.
SocketError
Defines error codes for the T:System.Net.Sockets.Socket class.
void Dispose()
Releases all resources used by the current instance of the T:System.Net.Sockets.Socket class.
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...
string Host
Gets the host name or string representation of the Internet Protocol (IP) address of the host.
ProtocolType ProtocolType
Gets the protocol type of the T:System.Net.Sockets.Socket.
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,...
Socket Accept()
Creates a new T:System.Net.Sockets.Socket for a newly created connection.
ProtocolType
Specifies the protocols that the T:System.Net.Sockets.Socket class supports.
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.
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....
bool Reset()
Sets the state of the event to nonsignaled, causing threads to block.
Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I...
FileShare
Contains constants for controlling the kind of access other T:System.IO.FileStream objects can have t...
Represents an asynchronous operation that can return a value.
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.
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....
int SendBufferSize
Gets or sets a value that specifies the size of the send buffer of the T:System.Net....
bool DisconnectAsync(SocketAsyncEventArgs e)
Begins an asynchronous request to disconnect from a remote endpoint.
static void SpinWait(int iterations)
Causes a thread to wait the number of times defined by the iterations parameter.
static bool OSSupportsIPv4
Indicates whether the underlying operating system and network adaptors support Internet Protocol vers...
Creates and controls a thread, sets its priority, and gets its status.