internal int ReceiveFrom_nochecks_exc (byte [] buf, int offset, int size, SocketFlags flags, ref EndPoint remote_end, bool throwOnError, out int error) { SocketAddress sockaddr = remote_end.Serialize(); int cnt = ReceiveFrom_internal (safe_handle, buf, offset, size, flags, ref sockaddr, out error); SocketError err = (SocketError) error; if (err != 0) { if (err != SocketError.WouldBlock && err != SocketError.InProgress) { is_connected = false; } else if (err == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set if (throwOnError) throw new SocketException ((int) SocketError.TimedOut, TIMEOUT_EXCEPTION_MSG); error = (int) SocketError.TimedOut; return 0; } if (throwOnError) throw new SocketException (error); return 0; } is_connected = true; is_bound = true; /* If sockaddr is null then we're a connection oriented protocol and should ignore the * remote_end parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */ if (sockaddr != null) { /* Stupidly, EndPoint.Create() is an instance method */ remote_end = remote_end.Create (sockaddr); } seed_endpoint = remote_end; return cnt; }
// Routine Description: // // BeginReceiveFrom - Async implimentation of RecvFrom call, // // Called when we want to start an async receive. // We kick off the receive, and if it completes synchronously we'll // call the callback. Otherwise we'll return an IASyncResult, which // the caller can use to wait on or retrieve the final status, as needed. // // Uses Winsock 2 overlapped I/O. // // Arguments: // // ReadBuffer - status line that we wish to parse // Index - Offset into ReadBuffer to begin reading from // Request - Size of Buffer to recv // Flags - Additonal Flags that may be passed to the underlying winsock call // remoteEP - EndPoint that are to receive from // Callback - Delegate function that holds callback, called on completeion of I/O // State - State used to track callback, set by caller, not required // // Return Value: // // IAsyncResult - Async result used to retreive result internal IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state) { if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "BeginReceiveFrom", ""); } if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (buffer == null) { throw new ArgumentNullException("buffer"); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } if (!CanTryAddressFamily(remoteEP.AddressFamily)) { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, remoteEP.AddressFamily, _addressFamily), "remoteEP"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } if (_rightEndPoint == null) { throw new InvalidOperationException(SR.net_sockets_mustbind); } // We don't do a CAS demand here because the contents of remoteEP aren't used by // WSARecvFrom; all that matters is that we generate a unique-to-this-call SocketAddress // with the right address family Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP); // Set up the result and set it to collect the context. OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback); asyncResult.StartPostingAsyncOp(false); // Start the ReceiveFrom. DoBeginReceiveFrom(buffer, offset, size, socketFlags, remoteEP, socketAddress, asyncResult); // Capture the context, maybe call the callback, and return. asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache); if (asyncResult.CompletedSynchronously && !asyncResult.SocketAddressOriginal.Equals(asyncResult.SocketAddress)) { try { remoteEP = remoteEP.Create(asyncResult.SocketAddress); } catch { } } if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "BeginReceiveFrom", asyncResult); } return asyncResult; }
// Routine Description: // // EndReceiveFrom - Called when I/O is done or the user wants to wait. If // the I/O isn't done, we'll wait for it to complete, and then we'll return // the bytes of I/O done. // // Arguments: // // AsyncResult - the AsyncResult Returned fron BeginReceiveFrom call // // Return Value: // // int - Number of bytes transferred internal int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint) { if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "EndReceiveFrom", asyncResult); } if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // Validate input parameters. if (endPoint == null) { throw new ArgumentNullException("endPoint"); } if (!CanTryAddressFamily(endPoint.AddressFamily)) { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, endPoint.AddressFamily, _addressFamily), "endPoint"); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, "asyncResult"); } if (castedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndReceiveFrom")); } Internals.SocketAddress socketAddressOriginal = SnapshotAndSerialize(ref endPoint); int bytesTransferred = (int)castedAsyncResult.InternalWaitForCompletion(); castedAsyncResult.EndCalled = true; // Update socket address size. castedAsyncResult.SocketAddress.InternalSize = castedAsyncResult.GetSocketAddressSize(); if (!socketAddressOriginal.Equals(castedAsyncResult.SocketAddress)) { try { endPoint = endPoint.Create(castedAsyncResult.SocketAddress); } catch { } } if (s_perfCountersEnabled) { if (bytesTransferred > 0) { SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesReceived, bytesTransferred); if (Transport == TransportType.Udp) { SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsReceived); } } } GlobalLog.Print("Socket#" + Logging.HashString(this) + "::EndReceiveFrom() bytesTransferred:" + bytesTransferred.ToString()); // Throw an appropriate SocketException if the native call failed asynchronously. if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success) { // Update the internal state of this socket according to the error before throwing. SocketException socketException = new SocketException(castedAsyncResult.ErrorCode); UpdateStatusAfterSocketError(socketException); if (s_loggingEnabled) { Logging.Exception(Logging.Sockets, this, "EndReceiveFrom", socketException); } throw socketException; } if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "EndReceiveFrom", bytesTransferred); } return bytesTransferred; }
/*++ Routine Description: EndReceiveFrom - Called when I/O is done or the user wants to wait. If the I/O isn't done, we'll wait for it to complete, and then we'll return the bytes of I/O done. Arguments: AsyncResult - the AsyncResult Returned fron BeginReceiveFrom call Return Value: int - Number of bytes transferred --*/ /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint) { if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "EndReceiveFrom", asyncResult); if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // // parameter validation // if (endPoint==null) { throw new ArgumentNullException("endPoint"); } if (!CanTryAddressFamily(endPoint.AddressFamily)) { throw new ArgumentException(SR.GetString(SR.net_InvalidEndPointAddressFamily, endPoint.AddressFamily, addressFamily), "endPoint"); } if (asyncResult==null) { throw new ArgumentNullException("asyncResult"); } OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult; if (castedAsyncResult==null || castedAsyncResult.AsyncObject!=this) { throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult"); } if (castedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndReceiveFrom")); } SocketAddress socketAddressOriginal = SnapshotAndSerialize(ref endPoint); int bytesTransferred = (int)castedAsyncResult.InternalWaitForCompletion(); castedAsyncResult.EndCalled = true; castedAsyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache); // Update socket address size castedAsyncResult.SocketAddress.SetSize(castedAsyncResult.GetSocketAddressSizePtr()); if (!socketAddressOriginal.Equals(castedAsyncResult.SocketAddress)) { try { endPoint = endPoint.Create(castedAsyncResult.SocketAddress); } catch { } } #if !FEATURE_PAL // perfcounter if (s_PerfCountersEnabled) { if (bytesTransferred>0) { NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, bytesTransferred); if (Transport==TransportType.Udp) { NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived); } } } #endif //!FEATURE_PAL GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::EndReceiveFrom() bytesTransferred:" + bytesTransferred.ToString()); // // if the asynchronous native call failed asynchronously // we'll throw a SocketException // if ((SocketError)castedAsyncResult.ErrorCode!=SocketError.Success) { // // update our internal state after this socket error and throw // SocketException socketException = new SocketException(castedAsyncResult.ErrorCode); UpdateStatusAfterSocketError(socketException); if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "EndReceiveFrom", socketException); throw socketException; } if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "EndReceiveFrom", bytesTransferred); return bytesTransferred; }
internal IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state) { if (s_loggingEnabled) { Logging.Enter(Logging.Sockets, this, "BeginReceiveMessageFrom", ""); } GlobalLog.Print("Socket#" + Logging.HashString(this) + "::BeginReceiveMessageFrom() size:" + size.ToString()); if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (buffer == null) { throw new ArgumentNullException("buffer"); } if (remoteEP == null) { throw new ArgumentNullException("remoteEP"); } if (!CanTryAddressFamily(remoteEP.AddressFamily)) { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, remoteEP.AddressFamily, _addressFamily), "remoteEP"); } if (offset < 0 || offset > buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size < 0 || size > buffer.Length - offset) { throw new ArgumentOutOfRangeException("size"); } if (_rightEndPoint == null) { throw new InvalidOperationException(SR.net_sockets_mustbind); } // Set up the result and set it to collect the context. ReceiveMessageOverlappedAsyncResult asyncResult = new ReceiveMessageOverlappedAsyncResult(this, state, callback); asyncResult.StartPostingAsyncOp(false); // Start the ReceiveFrom. EndPoint oldEndPoint = _rightEndPoint; // We don't do a CAS demand here because the contents of remoteEP aren't used by // WSARecvMsg; all that matters is that we generate a unique-to-this-call SocketAddress // with the right address family Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP); // Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to // avoid a Socket leak in case of error. SocketError errorCode = SocketError.SocketError; try { // Save a copy of the original EndPoint in the asyncResult. asyncResult.SocketAddressOriginal = IPEndPointExtensions.Serialize(remoteEP); SetReceivingPacketInformation(); if (_rightEndPoint == null) { _rightEndPoint = remoteEP; } errorCode = SocketPal.ReceiveMessageFromAsync(this, _handle, buffer, offset, size, socketFlags, socketAddress, asyncResult); if (errorCode != SocketError.Success) { // WSARecvMsg() will never return WSAEMSGSIZE directly, since a completion is queued in this case. We wouldn't be able // to handle this easily because of assumptions OverlappedAsyncResult makes about whether there would be a completion // or not depending on the error code. If WSAEMSGSIZE would have been normally returned, it returns WSA_IO_PENDING instead. // That same map is implemented here just in case. if (errorCode == SocketError.MessageSize) { GlobalLog.Assert("Socket#" + Logging.HashString(this) + "::BeginReceiveMessageFrom()|Returned WSAEMSGSIZE!"); errorCode = SocketError.IOPending; } } GlobalLog.Print("Socket#" + Logging.HashString(this) + "::BeginReceiveMessageFrom() Interop.Winsock.WSARecvMsg returns:" + errorCode.ToString() + " size:" + size.ToString() + " returning AsyncResult:" + Logging.HashString(asyncResult)); } catch (ObjectDisposedException) { _rightEndPoint = oldEndPoint; throw; } finally { errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode); } // Throw an appropriate SocketException if the native call fails synchronously. if (errorCode != SocketError.Success) { // Update the internal state of this socket according to the error before throwing. _rightEndPoint = oldEndPoint; SocketException socketException = new SocketException((int)errorCode); UpdateStatusAfterSocketError(socketException); if (s_loggingEnabled) { Logging.Exception(Logging.Sockets, this, "BeginReceiveMessageFrom", socketException); } throw socketException; } // Capture the context, maybe call the callback, and return. asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache); if (asyncResult.CompletedSynchronously && !asyncResult.SocketAddressOriginal.Equals(asyncResult.SocketAddress)) { try { remoteEP = remoteEP.Create(asyncResult.SocketAddress); } catch { } } GlobalLog.Print("Socket#" + Logging.HashString(this) + "::BeginReceiveMessageFrom() size:" + size.ToString() + " returning AsyncResult:" + Logging.HashString(asyncResult)); if (s_loggingEnabled) { Logging.Exit(Logging.Sockets, this, "BeginReceiveMessageFrom", asyncResult); } return asyncResult; }
internal int ReceiveFrom_nochecks_exc (byte [] buf, int offset, int size, SocketFlags flags, ref EndPoint remote_end, bool throwOnError, out int error) { SocketAddress sockaddr = remote_end.Serialize(); int cnt = RecvFrom_internal (socket, buf, offset, size, flags, ref sockaddr, out error); SocketError err = (SocketError) error; if (err != 0) { if (err != SocketError.WouldBlock && err != SocketError.InProgress) connected = false; else if (err == SocketError.WouldBlock && blocking) { // This might happen when ReceiveTimeout is set if (throwOnError) throw new SocketException ((int) SocketError.TimedOut, "Operation timed out"); error = (int) SocketError.TimedOut; return 0; } if (throwOnError) throw new SocketException (error); return 0; } connected = true; #if NET_2_0 isbound = true; #endif // If sockaddr is null then we're a connection // oriented protocol and should ignore the // remote_end parameter (see MSDN // documentation for Socket.ReceiveFrom(...) ) if ( sockaddr != null ) { // Stupidly, EndPoint.Create() is an // instance method remote_end = remote_end.Create (sockaddr); } seed_endpoint = remote_end; return cnt; }
public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state) { if (s_LoggingEnabled) Logging.Enter(Logging.Sockets, this, "BeginReceiveMessageFrom", ""); GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginReceiveMessageFrom() size:" + size.ToString()); if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (buffer==null) { throw new ArgumentNullException("buffer"); } if (remoteEP==null) { throw new ArgumentNullException("remoteEP"); } if (!CanTryAddressFamily(remoteEP.AddressFamily)) { throw new ArgumentException(SR.GetString(SR.net_InvalidEndPointAddressFamily, remoteEP.AddressFamily, addressFamily), "remoteEP"); } if (offset<0 || offset>buffer.Length) { throw new ArgumentOutOfRangeException("offset"); } if (size<0 || size>buffer.Length-offset) { throw new ArgumentOutOfRangeException("size"); } if (m_RightEndPoint==null) { throw new InvalidOperationException(SR.GetString(SR.net_sockets_mustbind)); } // Set up the result and set it to collect the context. ReceiveMessageOverlappedAsyncResult asyncResult = new ReceiveMessageOverlappedAsyncResult(this, state, callback); asyncResult.StartPostingAsyncOp(false); // Start the ReceiveFrom. EndPoint oldEndPoint = m_RightEndPoint; // We don't do a CAS demand here because the contents of remoteEP aren't used by // WSARecvMsg; all that matters is that we generate a unique-to-this-call SocketAddress // with the right address family SocketAddress socketAddress = SnapshotAndSerialize(ref remoteEP); // Guarantee to call CheckAsyncCallOverlappedResult if we call SetUnamangedStructures with a cache in order to // avoid a Socket leak in case of error. SocketError errorCode = SocketError.SocketError; try { asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags, ref Caches.ReceiveOverlappedCache); // save a copy of the original EndPoint in the asyncResult asyncResult.SocketAddressOriginal = remoteEP.Serialize(); int bytesTransfered; SetReceivingPacketInformation(); if (m_RightEndPoint == null) { m_RightEndPoint = remoteEP; } errorCode = (SocketError) WSARecvMsg( m_Handle, Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.m_MessageBuffer,0), out bytesTransfered, asyncResult.OverlappedHandle, IntPtr.Zero); if (errorCode!=SocketError.Success) { errorCode = (SocketError)Marshal.GetLastWin32Error(); // I have guarantees from Brad Williamson that WSARecvMsg() will never return WSAEMSGSIZE directly, since a completion // is queued in this case. We wouldn't be able to handle this easily because of assumptions OverlappedAsyncResult // makes about whether there would be a completion or not depending on the error code. If WSAEMSGSIZE would have been // normally returned, it returns WSA_IO_PENDING instead. That same map is implemented here just in case. if (errorCode == SocketError.MessageSize) { GlobalLog.Assert("Socket#" + ValidationHelper.HashString(this) + "::BeginReceiveMessageFrom()|Returned WSAEMSGSIZE!"); errorCode = SocketError.IOPending; } } GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginReceiveMessageFrom() UnsafeNclNativeMethods.OSSOCK.WSARecvMsg returns:" + errorCode.ToString() + " size:" + size.ToString() + " returning AsyncResult:" + ValidationHelper.HashString(asyncResult)); } catch (ObjectDisposedException) { m_RightEndPoint = oldEndPoint; throw; } finally { errorCode = asyncResult.CheckAsyncCallOverlappedResult(errorCode); } // // if the asynchronous native call fails synchronously // we'll throw a SocketException // if (errorCode!=SocketError.Success) { // // update our internal state after this socket error and throw // m_RightEndPoint = oldEndPoint; asyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache); SocketException socketException = new SocketException(errorCode); UpdateStatusAfterSocketError(socketException); if (s_LoggingEnabled) Logging.Exception(Logging.Sockets, this, "BeginReceiveMessageFrom", socketException); throw socketException; } // Capture the context, maybe call the callback, and return. asyncResult.FinishPostingAsyncOp(ref Caches.ReceiveClosureCache); if (asyncResult.CompletedSynchronously && !asyncResult.SocketAddressOriginal.Equals(asyncResult.SocketAddress)) { try { remoteEP = remoteEP.Create(asyncResult.SocketAddress); } catch { } } GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::BeginReceiveMessageFrom() size:" + size.ToString() + " returning AsyncResult:" + ValidationHelper.HashString(asyncResult)); if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "BeginReceiveMessageFrom", asyncResult); return asyncResult; }
/*++ Routine Description: EndReceiveFrom - Called when I/O is done or the user wants to wait. If the I/O isn't done, we'll wait for it to complete, and then we'll return the bytes of I/O done. Arguments: AsyncResult - the AsyncResult Returned fron BeginReceiveFrom call Return Value: int - Number of bytes transferred --*/ /// <include file='doc\Socket.uex' path='docs/doc[@for="Socket.EndReceiveFrom"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public int EndReceiveFrom(IAsyncResult asyncResult, ref EndPoint endPoint) { if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } // // parameter validation // if (endPoint==null) { throw new ArgumentNullException("endPoint"); } if (asyncResult==null) { throw new ArgumentNullException("asyncResult"); } OverlappedAsyncResult castedAsyncResult = asyncResult as OverlappedAsyncResult; if (castedAsyncResult==null || castedAsyncResult.AsyncObject!=this) { throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult)); } if (castedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndReceiveFrom")); } int bytesTransferred = (int)castedAsyncResult.InternalWaitForCompletion(); castedAsyncResult.EndCalled = true; // pick up the saved copy of the original EndPoint from the asyncResult if (!castedAsyncResult.m_SocketAddressOriginal.Equals(castedAsyncResult.m_SocketAddress)) { try { endPoint = endPoint.Create(castedAsyncResult.m_SocketAddress); } catch { } } GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::EndReceiveFrom() bytesTransferred:" + bytesTransferred.ToString()); // // if the asynchronous native call failed asynchronously // we'll throw a SocketException // if (castedAsyncResult.ErrorCode!=SocketErrors.Success) { // // update our internal state after this socket error and throw // UpdateStatusAfterSocketError(); throw new SocketException(castedAsyncResult.ErrorCode); } return bytesTransferred; }
public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP) { if (m_Handle == -1) { throw new ObjectDisposedException(); } byte[] address = remoteEP.Serialize().m_Buffer; int len = 0; len = NativeSocket.recvfrom(this, buffer, offset, size, (int)socketFlags, m_recvTimeout, ref address); SocketAddress socketAddress = new SocketAddress(address); remoteEP = remoteEP.Create(socketAddress); return len; }
/// <summary> /// Begins to asynchronously receive the specified number of bytes of data into the specified location of the data buffer, using the specified <see cref="T:System.Net.Sockets.SocketFlags"/>, and stores the endpoint and packet information.. /// </summary> /// /// <returns> /// An <see cref="T:System.IAsyncResult"/> that references the asynchronous read. /// </returns> /// <param name="buffer">An array of type <see cref="T:System.Byte"/> that is the storage location for the received data. </param><param name="offset">The zero-based position in the <paramref name="buffer"/> parameter at which to store the data.</param><param name="size">The number of bytes to receive. </param><param name="socketFlags">A bitwise combination of the <see cref="T:System.Net.Sockets.SocketFlags"/> values.</param><param name="remoteEP">An <see cref="T:System.Net.EndPoint"/> that represents the source of the data.</param><param name="callback">The <see cref="T:System.AsyncCallback"/> delegate.</param><param name="state">An object that contains state information for this request.</param><exception cref="T:System.ArgumentNullException"><paramref name="buffer"/> is null.-or- <paramref name="remoteEP"/> is null. </exception><exception cref="T:System.Net.Sockets.SocketException">An error occurred when attempting to access the socket. See the Remarks section for more information. </exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="offset"/> is less than 0.-or- <paramref name="offset"/> is greater than the length of <paramref name="buffer"/>.-or- <paramref name="size"/> is less than 0.-or- <paramref name="size"/> is greater than the length of <paramref name="buffer"/> minus the value of the <paramref name="offset"/> parameter. </exception><exception cref="T:System.ObjectDisposedException">The <see cref="T:System.Net.Sockets.Socket"/> has been closed. </exception><exception cref="T:System.NotSupportedException">The operating system is Windows 2000 or earlier, and this method requires Windows XP.</exception> public IAsyncResult BeginReceiveMessageFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state) { if (Socket.s_LoggingEnabled) Logging.Enter(Logging.Sockets, (object) this, "BeginReceiveMessageFrom", ""); if (this.CleanedUp) throw new ObjectDisposedException(this.GetType().FullName); if (buffer == null) throw new ArgumentNullException("buffer"); if (remoteEP == null) throw new ArgumentNullException("remoteEP"); if (!this.CanTryAddressFamily(remoteEP.AddressFamily)) { throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", (object) remoteEP.AddressFamily, (object) this.addressFamily), "remoteEP"); } else { if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (size < 0 || size > buffer.Length - offset) throw new ArgumentOutOfRangeException("size"); if (this.m_RightEndPoint == null) throw new InvalidOperationException(SR.GetString("net_sockets_mustbind")); ReceiveMessageOverlappedAsyncResult overlappedAsyncResult = new ReceiveMessageOverlappedAsyncResult(this, state, callback); overlappedAsyncResult.StartPostingAsyncOp(false); EndPoint endPoint = this.m_RightEndPoint; SocketAddress socketAddress = this.SnapshotAndSerialize(ref remoteEP); SocketError socketError = SocketError.SocketError; try { overlappedAsyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags, ref this.Caches.ReceiveOverlappedCache); overlappedAsyncResult.SocketAddressOriginal = remoteEP.Serialize(); this.SetReceivingPacketInformation(); if (this.m_RightEndPoint == null) this.m_RightEndPoint = remoteEP; int bytesTransferred; socketError = this.WSARecvMsg(this.m_Handle, Marshal.UnsafeAddrOfPinnedArrayElement((Array) overlappedAsyncResult.m_MessageBuffer, 0), out bytesTransferred, overlappedAsyncResult.OverlappedHandle, IntPtr.Zero); if (socketError != SocketError.Success) { socketError = (SocketError) Marshal.GetLastWin32Error(); if (socketError == SocketError.MessageSize) socketError = SocketError.IOPending; } } catch (ObjectDisposedException ex) { this.m_RightEndPoint = endPoint; throw; } finally { socketError = overlappedAsyncResult.CheckAsyncCallOverlappedResult(socketError); } if (socketError != SocketError.Success) { this.m_RightEndPoint = endPoint; overlappedAsyncResult.ExtractCache(ref this.Caches.ReceiveOverlappedCache); SocketException socketException = new SocketException(socketError); this.UpdateStatusAfterSocketError(socketException); if (Socket.s_LoggingEnabled) Logging.Exception(Logging.Sockets, (object) this, "BeginReceiveMessageFrom", (Exception) socketException); throw socketException; } else { overlappedAsyncResult.FinishPostingAsyncOp(ref this.Caches.ReceiveClosureCache); if (overlappedAsyncResult.CompletedSynchronously) { if (!overlappedAsyncResult.SocketAddressOriginal.Equals((object) overlappedAsyncResult.SocketAddress)) { try { remoteEP = remoteEP.Create(overlappedAsyncResult.SocketAddress); } catch { } } } if (Socket.s_LoggingEnabled) Logging.Exit(Logging.Sockets, (object) this, "BeginReceiveMessageFrom", (object) overlappedAsyncResult); return (IAsyncResult) overlappedAsyncResult; } } }
/// <summary> /// Ends a pending asynchronous read from a specific endpoint. This method also reveals more information about the packet than <see cref="M:System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@)"/>. /// </summary> /// /// <returns> /// If successful, the number of bytes received. If unsuccessful, returns 0. /// </returns> /// <param name="asyncResult">An <see cref="T:System.IAsyncResult"/> that stores state information and any user defined data for this asynchronous operation.</param><param name="socketFlags">A bitwise combination of the <see cref="T:System.Net.Sockets.SocketFlags"/> values for the received packet.</param><param name="endPoint">The source <see cref="T:System.Net.EndPoint"/>.</param><param name="ipPacketInformation">The <see cref="T:System.Net.IPAddress"/> and interface of the received packet.</param><exception cref="T:System.ArgumentNullException"><paramref name="asyncResult"/> is null-or- <paramref name="endPoint"/> is null. </exception><exception cref="T:System.ArgumentException"><paramref name="asyncResult"/> was not returned by a call to the <see cref="M:System.Net.Sockets.Socket.BeginReceiveMessageFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object)"/> method. </exception><exception cref="T:System.InvalidOperationException"><see cref="M:System.Net.Sockets.Socket.EndReceiveMessageFrom(System.IAsyncResult,System.Net.Sockets.SocketFlags@,System.Net.EndPoint@,System.Net.Sockets.IPPacketInformation@)"/> was previously called for the asynchronous read. </exception><exception cref="T:System.Net.Sockets.SocketException">An error occurred when attempting to access the socket. See the Remarks section for more information. </exception><exception cref="T:System.ObjectDisposedException">The <see cref="T:System.Net.Sockets.Socket"/> has been closed. </exception> public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation) { if (Socket.s_LoggingEnabled) Logging.Enter(Logging.Sockets, (object) this, "EndReceiveMessageFrom", (object) asyncResult); if (this.CleanedUp) throw new ObjectDisposedException(this.GetType().FullName); if (endPoint == null) throw new ArgumentNullException("endPoint"); if (!this.CanTryAddressFamily(endPoint.AddressFamily)) { throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", (object) endPoint.AddressFamily, (object) this.addressFamily), "endPoint"); } else { if (asyncResult == null) throw new ArgumentNullException("asyncResult"); ReceiveMessageOverlappedAsyncResult overlappedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult; if (overlappedAsyncResult == null || overlappedAsyncResult.AsyncObject != this) throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult"); if (overlappedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", new object[1] { (object) "EndReceiveMessageFrom" })); } else { SocketAddress socketAddress = this.SnapshotAndSerialize(ref endPoint); int num = (int) overlappedAsyncResult.InternalWaitForCompletion(); overlappedAsyncResult.EndCalled = true; overlappedAsyncResult.ExtractCache(ref this.Caches.ReceiveOverlappedCache); overlappedAsyncResult.SocketAddress.SetSize(overlappedAsyncResult.GetSocketAddressSizePtr()); if (!socketAddress.Equals((object) overlappedAsyncResult.SocketAddress)) { try { endPoint = endPoint.Create(overlappedAsyncResult.SocketAddress); } catch { } } if (Socket.s_PerfCountersEnabled && num > 0) { NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, (long) num); if (this.Transport == TransportType.Udp) NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived); } if (overlappedAsyncResult.ErrorCode != 0 && overlappedAsyncResult.ErrorCode != 10040) { SocketException socketException = new SocketException(overlappedAsyncResult.ErrorCode); this.UpdateStatusAfterSocketError(socketException); if (Socket.s_LoggingEnabled) Logging.Exception(Logging.Sockets, (object) this, "EndReceiveMessageFrom", (Exception) socketException); throw socketException; } else { socketFlags = overlappedAsyncResult.m_flags; ipPacketInformation = overlappedAsyncResult.m_IPPacketInformation; if (Socket.s_LoggingEnabled) Logging.Exit(Logging.Sockets, (object) this, "EndReceiveMessageFrom", (object) num); return num; } } } }
public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state) { if (Socket.s_LoggingEnabled) Logging.Enter(Logging.Sockets, (object) this, "BeginReceiveFrom", ""); if (this.CleanedUp) throw new ObjectDisposedException(this.GetType().FullName); if (buffer == null) throw new ArgumentNullException("buffer"); if (remoteEP == null) throw new ArgumentNullException("remoteEP"); if (!this.CanTryAddressFamily(remoteEP.AddressFamily)) { throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", (object) remoteEP.AddressFamily, (object) this.addressFamily), "remoteEP"); } else { if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException("offset"); if (size < 0 || size > buffer.Length - offset) throw new ArgumentOutOfRangeException("size"); if (this.m_RightEndPoint == null) throw new InvalidOperationException(SR.GetString("net_sockets_mustbind")); SocketAddress socketAddress = this.SnapshotAndSerialize(ref remoteEP); OverlappedAsyncResult asyncResult = new OverlappedAsyncResult(this, state, callback); asyncResult.StartPostingAsyncOp(false); this.DoBeginReceiveFrom(buffer, offset, size, socketFlags, remoteEP, socketAddress, asyncResult); asyncResult.FinishPostingAsyncOp(ref this.Caches.ReceiveClosureCache); if (asyncResult.CompletedSynchronously) { if (!asyncResult.SocketAddressOriginal.Equals((object) asyncResult.SocketAddress)) { try { remoteEP = remoteEP.Create(asyncResult.SocketAddress); } catch { } } } if (Socket.s_LoggingEnabled) Logging.Exit(Logging.Sockets, (object) this, "BeginReceiveFrom", (object) asyncResult); return (IAsyncResult) asyncResult; } }
public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this, asyncResult); if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (endPoint == null) { throw new ArgumentNullException(nameof(endPoint)); } if (!CanTryAddressFamily(endPoint.AddressFamily)) { throw new ArgumentException(SR.Format(SR.net_InvalidEndPointAddressFamily, endPoint.AddressFamily, _addressFamily), nameof(endPoint)); } if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } ReceiveMessageOverlappedAsyncResult castedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (castedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndReceiveMessageFrom")); } Internals.SocketAddress socketAddressOriginal = SnapshotAndSerialize(ref endPoint); int bytesTransferred = castedAsyncResult.InternalWaitForCompletionInt32Result(); castedAsyncResult.EndCalled = true; // Update socket address size. castedAsyncResult.SocketAddress.InternalSize = castedAsyncResult.GetSocketAddressSize(); if (!socketAddressOriginal.Equals(castedAsyncResult.SocketAddress)) { try { endPoint = endPoint.Create(castedAsyncResult.SocketAddress); } catch { } } if (s_perfCountersEnabled) { if (bytesTransferred > 0) { SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesReceived, bytesTransferred); if (Transport == TransportType.Udp) { SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsReceived); } } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"bytesTransferred:{bytesTransferred}"); // Throw an appropriate SocketException if the native call failed asynchronously. if ((SocketError)castedAsyncResult.ErrorCode != SocketError.Success && (SocketError)castedAsyncResult.ErrorCode != SocketError.MessageSize) { // Update the internal state of this socket according to the error before throwing. SocketException socketException = new SocketException(castedAsyncResult.ErrorCode); UpdateStatusAfterSocketError(socketException); if (NetEventSource.IsEnabled) NetEventSource.Error(this, socketException); throw socketException; } socketFlags = castedAsyncResult.SocketFlags; ipPacketInformation = castedAsyncResult.IPPacketInformation; if (NetEventSource.IsEnabled) NetEventSource.Exit(this, bytesTransferred); return bytesTransferred; }
internal int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, out SocketError errorCode) { SocketAddress sockaddr = remoteEP.Serialize(); int nativeError; int cnt = ReceiveFrom_internal (m_Handle, buffer, offset, size, socketFlags, ref sockaddr, out nativeError, is_blocking); errorCode = (SocketError) nativeError; if (errorCode != SocketError.Success) { if (errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) { is_connected = false; } else if (errorCode == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set errorCode = SocketError.TimedOut; } return 0; } is_connected = true; is_bound = true; /* If sockaddr is null then we're a connection oriented protocol and should ignore the * remoteEP parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */ if (sockaddr != null) { /* Stupidly, EndPoint.Create() is an instance method */ remoteEP = remoteEP.Create (sockaddr); } seed_endpoint = remoteEP; return cnt; }
public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation) { if(Logging.On)Logging.Enter(Logging.Sockets, this, "EndReceiveMessageFrom", asyncResult); if (CleanedUp) { throw new ObjectDisposedException(this.GetType().FullName); } if (endPoint==null) { throw new ArgumentNullException("endPoint"); } if (asyncResult==null) { throw new ArgumentNullException("asyncResult"); } ReceiveMessageOverlappedAsyncResult castedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult; if (castedAsyncResult==null || castedAsyncResult.AsyncObject!=this) { throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult"); } if (castedAsyncResult.EndCalled) { throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndReceiveMessageFrom")); } int bytesTransferred = (int)castedAsyncResult.InternalWaitForCompletion(); castedAsyncResult.EndCalled = true; castedAsyncResult.ExtractCache(ref Caches.ReceiveOverlappedCache); // Update socket address size castedAsyncResult.SocketAddress.SetSize(castedAsyncResult.GetSocketAddressSizePtr()); // pick up the saved copy of the original EndPoint from the asyncResult SocketAddress socketAddressOriginal = endPoint.Serialize(); if (!socketAddressOriginal.Equals(castedAsyncResult.SocketAddress)) { try { endPoint = endPoint.Create(castedAsyncResult.SocketAddress); } catch { } } GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::EndReceiveMessageFrom() bytesTransferred:" + bytesTransferred.ToString()); // // if the asynchronous native call failed asynchronously // we'll throw a SocketException // if ((SocketError)castedAsyncResult.ErrorCode!=SocketError.Success && (SocketError)castedAsyncResult.ErrorCode != SocketError.MessageSize) { // // update our internal state after this socket error and throw // SocketException socketException = new SocketException(castedAsyncResult.ErrorCode); UpdateStatusAfterSocketError(socketException); if(Logging.On)Logging.Exception(Logging.Sockets, this, "EndReceiveMessageFrom", socketException); throw socketException; } socketFlags = castedAsyncResult.m_flags; ipPacketInformation = castedAsyncResult.m_IPPacketInformation; if(Logging.On)Logging.Exit(Logging.Sockets, this, "EndReceiveMessageFrom", bytesTransferred); return bytesTransferred; }
public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation) { if (s_LoggingEnabled) { Logging.Enter(Logging.Sockets, this, "EndReceiveMessageFrom", asyncResult); } if (this.CleanedUp) { throw new ObjectDisposedException(base.GetType().FullName); } if (endPoint == null) { throw new ArgumentNullException("endPoint"); } if (endPoint.AddressFamily != this.addressFamily) { throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", new object[] { endPoint.AddressFamily, this.addressFamily }), "endPoint"); } if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } ReceiveMessageOverlappedAsyncResult result = asyncResult as ReceiveMessageOverlappedAsyncResult; if ((result == null) || (result.AsyncObject != this)) { throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult"); } if (result.EndCalled) { throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", new object[] { "EndReceiveMessageFrom" })); } SocketAddress address = this.CallSerializeCheckDnsEndPoint(endPoint); int retObject = (int) result.InternalWaitForCompletion(); result.EndCalled = true; result.ExtractCache(ref this.Caches.ReceiveOverlappedCache); result.SocketAddress.SetSize(result.GetSocketAddressSizePtr()); if (!address.Equals(result.SocketAddress)) { try { endPoint = endPoint.Create(result.SocketAddress); } catch { } } if (s_PerfCountersEnabled && (retObject > 0)) { NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketBytesReceived, (long) retObject); if (this.Transport == TransportType.Udp) { NetworkingPerfCounters.Instance.Increment(NetworkingPerfCounterName.SocketDatagramsReceived); } } if ((result.ErrorCode != 0) && (result.ErrorCode != 0x2738)) { SocketException socketException = new SocketException(result.ErrorCode); this.UpdateStatusAfterSocketError(socketException); if (s_LoggingEnabled) { Logging.Exception(Logging.Sockets, this, "EndReceiveMessageFrom", socketException); } throw socketException; } socketFlags = result.m_flags; ipPacketInformation = result.m_IPPacketInformation; if (s_LoggingEnabled) { Logging.Exit(Logging.Sockets, this, "EndReceiveMessageFrom", retObject); } return retObject; }