Inheritance: BaseOverlappedAsyncResult
        public static SocketError ReceiveMessageFrom(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int size, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
        {
            ReceiveMessageOverlappedAsyncResult asyncResult = new ReceiveMessageOverlappedAsyncResult(socket, null, null);

            asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags);

            SocketError errorCode = SocketError.Success;

            bytesTransferred = 0;
            try
            {
                // This can throw ObjectDisposedException (retrieving the delegate AND resolving the handle).
                if (socket.WSARecvMsgBlocking(
                        handle.DangerousGetHandle(),
                        Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
                        out bytesTransferred,
                        IntPtr.Zero,
                        IntPtr.Zero) == SocketError.SocketError)
                {
                    errorCode = (SocketError)Marshal.GetLastWin32Error();
                }
            }
            finally
            {
                asyncResult.SyncReleaseUnmanagedStructures();
            }

            socketFlags         = asyncResult.SocketFlags;
            receiveAddress      = asyncResult.SocketAddress;
            ipPacketInformation = asyncResult.IPPacketInformation;

            return(errorCode);
        }
Example #2
0
        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;
        }
        public static unsafe SocketError ReceiveMessageFromAsync(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult)
        {
            asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, socketFlags);

            int         bytesTransfered;
            SocketError errorCode = (SocketError)socket.WSARecvMsg(
                handle,
                Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
                out bytesTransfered,
                asyncResult.OverlappedHandle,
                IntPtr.Zero);

            if (errorCode != SocketError.Success)
            {
                errorCode = GetLastSocketError();
            }

            return(errorCode);
        }
Example #4
0
        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;
        }
Example #5
0
        public static SocketError ReceiveMessageFromAsync(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult)
        {
            asyncResult.SocketAddress = socketAddress;

            bool isIPv4, isIPv6;
            Socket.GetIPProtocolInformation(((Socket)asyncResult.AsyncObject).AddressFamily, socketAddress, out isIPv4, out isIPv6);

            return handle.AsyncContext.ReceiveMessageFromAsync(buffer, offset, count, socketFlags, socketAddress.Buffer, socketAddress.InternalSize, isIPv4, isIPv6, asyncResult.CompletionCallback);
        }
Example #6
0
        public static unsafe SocketError ReceiveMessageFromAsync(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult)
        {
            asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, socketFlags);
            try
            {
                int         bytesTransfered;
                SocketError errorCode = (SocketError)socket.WSARecvMsg(
                    handle,
                    Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
                    out bytesTransfered,
                    asyncResult.DangerousOverlappedPointer, // SafeHandle was just created in SetUnmanagedStructures
                    IntPtr.Zero);

                return(asyncResult.ProcessOverlappedResult(errorCode == SocketError.Success, bytesTransfered));
            }
            catch
            {
                asyncResult.ReleaseUnmanagedStructures();
                throw;
            }
        }
Example #7
0
        /// <devdoc>
        ///    <para>Receives a datagram into a specific location in the data buffer and stores
        ///       the end point.</para>
        /// </devdoc>
        public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation) {
            if(s_LoggingEnabled)Logging.Enter(Logging.Sockets, this, "ReceiveMessageFrom", "");

            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));
            }


            ValidateBlockingMode();

            // 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
            EndPoint endPointSnapshot = remoteEP;
            SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);

            ReceiveMessageOverlappedAsyncResult asyncResult = new ReceiveMessageOverlappedAsyncResult(this,null,null);
            asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags);

            // save a copy of the original EndPoint
            SocketAddress socketAddressOriginal = endPointSnapshot.Serialize();

            //setup structure
            int bytesTransfered = 0;
            SocketError errorCode = SocketError.Success;

            SetReceivingPacketInformation();

            try
            {
                // This can throw ObjectDisposedException (retrieving the delegate AND resolving the handle).
                if (WSARecvMsg_Blocking(
                    m_Handle.DangerousGetHandle(),
                    Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.m_MessageBuffer,0),
                    out bytesTransfered,
                    IntPtr.Zero,
                    IntPtr.Zero) == SocketError.SocketError)
                {
                    errorCode =  (SocketError)Marshal.GetLastWin32Error();
                }
            }
            finally {
                asyncResult.SyncReleaseUnmanagedStructures();
            }


            //
            // if the native call fails we'll throw a SocketException
            //
            if (errorCode!=SocketError.Success && errorCode != SocketError.MessageSize) {
                //
                // update our internal state after this socket error and throw
                //
                SocketException socketException = new SocketException(errorCode);
                UpdateStatusAfterSocketError(socketException);
                if(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "ReceiveMessageFrom", socketException);
                throw socketException;
            }


            if (!socketAddressOriginal.Equals(asyncResult.m_SocketAddress))
            {
                try {
                    remoteEP = endPointSnapshot.Create(asyncResult.m_SocketAddress);
                }
                catch {
                }
                if (m_RightEndPoint==null) {
                    //
                    // save a copy of the EndPoint so we can use it for Create()
                    //
                    m_RightEndPoint = endPointSnapshot;
                }
            }

            socketFlags = asyncResult.m_flags;
            ipPacketInformation = asyncResult.m_IPPacketInformation;

            if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "ReceiveMessageFrom", errorCode);
            return bytesTransfered;
        }
Example #8
0
        public static SocketError ReceiveMessageFrom(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int size, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
        {
            ReceiveMessageOverlappedAsyncResult asyncResult = new ReceiveMessageOverlappedAsyncResult(socket, null, null);
            asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags);

            SocketError errorCode = SocketError.Success;

            bytesTransferred = 0;
            try
            {
                // This can throw ObjectDisposedException (retrieving the delegate AND resolving the handle).
                if (socket.WSARecvMsgBlocking(
                    handle.DangerousGetHandle(),
                    Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
                    out bytesTransferred,
                    IntPtr.Zero,
                    IntPtr.Zero) == SocketError.SocketError)
                {
                    errorCode = (SocketError)Marshal.GetLastWin32Error();
                }
            }
            finally
            {
                asyncResult.SyncReleaseUnmanagedStructures();
            }

            socketFlags = asyncResult.SocketFlags;
            receiveAddress = asyncResult.SocketAddress;
            ipPacketInformation = asyncResult.IPPacketInformation;

            return errorCode;
        }
Example #9
0
        public static unsafe SocketError ReceiveMessageFromAsync(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, SocketFlags socketFlags, Internals.SocketAddress socketAddress, ReceiveMessageOverlappedAsyncResult asyncResult)
        {
            asyncResult.SetUnmanagedStructures(buffer, offset, count, socketAddress, socketFlags);

            int bytesTransfered;
            SocketError errorCode = (SocketError)socket.WSARecvMsg(
                handle,
                Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult._messageBuffer, 0),
                out bytesTransfered,
                asyncResult.OverlappedHandle,
                IntPtr.Zero);

            if (errorCode != SocketError.Success)
            {
                errorCode = GetLastSocketError();
            }

            return errorCode;
        }
Example #10
0
 /// <summary>
 /// Receives 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>
 /// The number of bytes received.
 /// </returns>
 /// <param name="buffer">An array of type <see cref="T:System.Byte"/> that is the storage location for received data.</param><param name="offset">The position in the <paramref name="buffer"/> parameter to store the received 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"/>, passed by reference, that represents the remote server.</param><param name="ipPacketInformation">An <see cref="T:System.Net.Sockets.IPPacketInformation"/> holding address and interface information.</param><exception cref="T:System.ArgumentNullException"><paramref name="buffer"/> is null.- or- <paramref name="remoteEP"/> is null. </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 the <paramref name="buffer"/> minus the value of the offset parameter. </exception><exception cref="T:System.Net.Sockets.SocketException"><paramref name="socketFlags"/> is not a valid combination of values.-or- The <see cref="P:System.Net.Sockets.Socket.LocalEndPoint"/> property was not set.-or- The .NET Framework is running on an AMD 64-bit processor.-or- 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><exception cref="T:System.NotSupportedException">The operating system is Windows 2000 or earlier, and this method requires Windows XP.</exception>
 public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
 {
     if (Socket.s_LoggingEnabled)
     Logging.Enter(Logging.Sockets, (object) this, "ReceiveMessageFrom", "");
       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"));
     this.ValidateBlockingMode();
     EndPoint remoteEP1 = remoteEP;
     SocketAddress socketAddress1 = this.SnapshotAndSerialize(ref remoteEP1);
     ReceiveMessageOverlappedAsyncResult overlappedAsyncResult = new ReceiveMessageOverlappedAsyncResult(this, (object) null, (AsyncCallback) null);
     overlappedAsyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress1, socketFlags);
     SocketAddress socketAddress2 = remoteEP1.Serialize();
     int bytesTransferred = 0;
     SocketError socketError = SocketError.Success;
     this.SetReceivingPacketInformation();
     try
     {
       if (this.WSARecvMsg_Blocking(this.m_Handle.DangerousGetHandle(), Marshal.UnsafeAddrOfPinnedArrayElement((Array) overlappedAsyncResult.m_MessageBuffer, 0), out bytesTransferred, IntPtr.Zero, IntPtr.Zero) == SocketError.SocketError)
     socketError = (SocketError) Marshal.GetLastWin32Error();
     }
     finally
     {
       overlappedAsyncResult.SyncReleaseUnmanagedStructures();
     }
     if (socketError != SocketError.Success && socketError != SocketError.MessageSize)
     {
       SocketException socketException = new SocketException(socketError);
       this.UpdateStatusAfterSocketError(socketException);
       if (Socket.s_LoggingEnabled)
     Logging.Exception(Logging.Sockets, (object) this, "ReceiveMessageFrom", (Exception) socketException);
       throw socketException;
     }
     else
     {
       if (!socketAddress2.Equals((object) overlappedAsyncResult.m_SocketAddress))
       {
     try
     {
       remoteEP = remoteEP1.Create(overlappedAsyncResult.m_SocketAddress);
     }
     catch
     {
     }
     if (this.m_RightEndPoint == null)
       this.m_RightEndPoint = remoteEP1;
       }
       socketFlags = overlappedAsyncResult.m_flags;
       ipPacketInformation = overlappedAsyncResult.m_IPPacketInformation;
       if (Socket.s_LoggingEnabled)
     Logging.Exit(Logging.Sockets, (object) this, "ReceiveMessageFrom", (object) socketError);
       return bytesTransferred;
     }
       }
 }
Example #11
0
 /// <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;
     }
       }
 }
Example #12
0
        /// <devdoc>
        ///    <para>Receives a datagram into a specific location in the data buffer and stores
        ///       the end point.</para>
        /// </devdoc>
        public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
        {
            if(Logging.On)Logging.Enter(Logging.Sockets, this, "ReceiveMessageFrom", "");

            if (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            if (buffer==null) {
                throw new ArgumentNullException("buffer");
            }
            if (remoteEP==null) {
                throw new ArgumentNullException("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));
            }

            ValidateBlockingMode();

            // This will check the permissions for connect.
            EndPoint endPointSnapshot = remoteEP;
            SocketAddress socketAddress = CheckCacheRemote(ref endPointSnapshot, false);

            ReceiveMessageOverlappedAsyncResult asyncResult = new ReceiveMessageOverlappedAsyncResult(this,null,null);
            asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags);

            // save a copy of the original EndPoint
            SocketAddress socketAddressOriginal = endPointSnapshot.Serialize();

            //setup structure
            int bytesTransfered = 0;
            SocketError errorCode = SocketError.Success;

            if(addressFamily == AddressFamily.InterNetwork) {
                SetSocketOption(SocketOptionLevel.IP,SocketOptionName.PacketInformation,true);
            }
            else if (addressFamily == AddressFamily.InterNetworkV6){
                SetSocketOption(SocketOptionLevel.IPv6,SocketOptionName.PacketInformation,true);
            }

            try
            {
                // This can throw ObjectDisposedException (retrieving the delegate AND resolving the handle).
                if (WSARecvMsg_Blocking(
                    m_Handle.DangerousGetHandle(),
                    Marshal.UnsafeAddrOfPinnedArrayElement(asyncResult.m_MessageBuffer,0),
                    out bytesTransfered,
                    IntPtr.Zero,
                    IntPtr.Zero) == SocketError.SocketError)
                {
                    errorCode =  (SocketError)Marshal.GetLastWin32Error();
                }
            }
            finally {
                asyncResult.SyncReleaseUnmanagedStructures();
            }

            //
            // if the native call fails we'll throw a SocketException
            //
            if (errorCode!=SocketError.Success && errorCode != SocketError.MessageSize) {
                //
                // update our internal state after this socket error and throw
                //
                SocketException socketException = new SocketException(errorCode);
                UpdateStatusAfterSocketError(socketException);
                if(Logging.On)Logging.Exception(Logging.Sockets, this, "ReceiveMessageFrom", socketException);
                throw socketException;
            }

            if (!socketAddressOriginal.Equals(asyncResult.m_SocketAddress))
            {
                try {
                    remoteEP = endPointSnapshot.Create(asyncResult.m_SocketAddress);
                }
                catch {
                }
                if (m_RightEndPoint==null) {
                    //
                    // save a copy of the EndPoint so we can use it for Create()
                    //
                    m_RightEndPoint = endPointSnapshot;
                }
            }

            socketFlags = asyncResult.m_flags;
            ipPacketInformation = asyncResult.m_IPPacketInformation;

            if(Logging.On)Logging.Exit(Logging.Sockets, this, "ReceiveMessageFrom", errorCode);
            return bytesTransfered;
        }
 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", "");
     }
     if (this.CleanedUp)
     {
         throw new ObjectDisposedException(base.GetType().FullName);
     }
     if (!ComNetOS.IsPostWin2K)
     {
         throw new PlatformNotSupportedException(SR.GetString("WinXPRequired"));
     }
     if (buffer == null)
     {
         throw new ArgumentNullException("buffer");
     }
     if (remoteEP == null)
     {
         throw new ArgumentNullException("remoteEP");
     }
     if (remoteEP.AddressFamily != this.addressFamily)
     {
         throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", new object[] { remoteEP.AddressFamily, this.addressFamily }), "remoteEP");
     }
     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 retObject = new ReceiveMessageOverlappedAsyncResult(this, state, callback);
     retObject.StartPostingAsyncOp(false);
     EndPoint rightEndPoint = this.m_RightEndPoint;
     EndPoint point2 = remoteEP;
     SocketAddress socketAddress = this.SnapshotAndSerialize(ref point2);
     SocketError socketError = SocketError.SocketError;
     try
     {
         int num;
         retObject.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags, ref this.Caches.ReceiveOverlappedCache);
         retObject.SocketAddressOriginal = point2.Serialize();
         this.SetReceivingPacketInformation();
         if (this.m_RightEndPoint == null)
         {
             this.m_RightEndPoint = point2;
         }
         socketError = this.WSARecvMsg(this.m_Handle, Marshal.UnsafeAddrOfPinnedArrayElement(retObject.m_MessageBuffer, 0), out num, retObject.OverlappedHandle, IntPtr.Zero);
         if (socketError != SocketError.Success)
         {
             socketError = (SocketError) Marshal.GetLastWin32Error();
             if (socketError == SocketError.MessageSize)
             {
                 socketError = SocketError.IOPending;
             }
         }
     }
     catch (ObjectDisposedException)
     {
         this.m_RightEndPoint = rightEndPoint;
         throw;
     }
     finally
     {
         socketError = retObject.CheckAsyncCallOverlappedResult(socketError);
     }
     if (socketError != SocketError.Success)
     {
         this.m_RightEndPoint = rightEndPoint;
         retObject.ExtractCache(ref this.Caches.ReceiveOverlappedCache);
         SocketException socketException = new SocketException(socketError);
         this.UpdateStatusAfterSocketError(socketException);
         if (s_LoggingEnabled)
         {
             Logging.Exception(Logging.Sockets, this, "BeginReceiveMessageFrom", socketException);
         }
         throw socketException;
     }
     retObject.FinishPostingAsyncOp(ref this.Caches.ReceiveClosureCache);
     if (retObject.CompletedSynchronously && !retObject.SocketAddressOriginal.Equals(retObject.SocketAddress))
     {
         try
         {
             remoteEP = point2.Create(retObject.SocketAddress);
         }
         catch
         {
         }
     }
     if (s_LoggingEnabled)
     {
         Logging.Exit(Logging.Sockets, this, "BeginReceiveMessageFrom", retObject);
     }
     return retObject;
 }
 public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
 {
     if (s_LoggingEnabled)
     {
         Logging.Enter(Logging.Sockets, this, "ReceiveMessageFrom", "");
     }
     if (this.CleanedUp)
     {
         throw new ObjectDisposedException(base.GetType().FullName);
     }
     if (!ComNetOS.IsPostWin2K)
     {
         throw new PlatformNotSupportedException(SR.GetString("WinXPRequired"));
     }
     if (buffer == null)
     {
         throw new ArgumentNullException("buffer");
     }
     if (remoteEP == null)
     {
         throw new ArgumentNullException("remoteEP");
     }
     if (remoteEP.AddressFamily != this.addressFamily)
     {
         throw new ArgumentException(SR.GetString("net_InvalidEndPointAddressFamily", new object[] { remoteEP.AddressFamily, this.addressFamily }), "remoteEP");
     }
     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"));
     }
     this.ValidateBlockingMode();
     EndPoint point = remoteEP;
     SocketAddress socketAddress = this.SnapshotAndSerialize(ref point);
     ReceiveMessageOverlappedAsyncResult result = new ReceiveMessageOverlappedAsyncResult(this, null, null);
     result.SetUnmanagedStructures(buffer, offset, size, socketAddress, socketFlags);
     SocketAddress address2 = point.Serialize();
     int bytesTransferred = 0;
     SocketError success = SocketError.Success;
     this.SetReceivingPacketInformation();
     try
     {
         if (this.WSARecvMsg_Blocking(this.m_Handle.DangerousGetHandle(), Marshal.UnsafeAddrOfPinnedArrayElement(result.m_MessageBuffer, 0), out bytesTransferred, IntPtr.Zero, IntPtr.Zero) == SocketError.SocketError)
         {
             success = (SocketError) Marshal.GetLastWin32Error();
         }
     }
     finally
     {
         result.SyncReleaseUnmanagedStructures();
     }
     switch (success)
     {
         case SocketError.Success:
         case SocketError.MessageSize:
             if (!address2.Equals(result.m_SocketAddress))
             {
                 try
                 {
                     remoteEP = point.Create(result.m_SocketAddress);
                 }
                 catch
                 {
                 }
                 if (this.m_RightEndPoint == null)
                 {
                     this.m_RightEndPoint = point;
                 }
             }
             socketFlags = result.m_flags;
             ipPacketInformation = result.m_IPPacketInformation;
             if (s_LoggingEnabled)
             {
                 Logging.Exit(Logging.Sockets, this, "ReceiveMessageFrom", success);
             }
             return bytesTransferred;
     }
     SocketException socketException = new SocketException(success);
     this.UpdateStatusAfterSocketError(socketException);
     if (s_LoggingEnabled)
     {
         Logging.Exception(Logging.Sockets, this, "ReceiveMessageFrom", socketException);
     }
     throw socketException;
 }