private unsafe void InitIPPacketInformation()
 {
     IPAddress address = null;
     if (this.m_ControlBuffer.Length == s_ControlDataSize)
     {
         UnsafeNclNativeMethods.OSSOCK.ControlData data = (UnsafeNclNativeMethods.OSSOCK.ControlData) Marshal.PtrToStructure(this.m_Message.controlBuffer.Pointer, typeof(UnsafeNclNativeMethods.OSSOCK.ControlData));
         if (data.length != UIntPtr.Zero)
         {
             address = new IPAddress((long) data.address);
         }
         this.m_IPPacketInformation = new IPPacketInformation((address != null) ? address : IPAddress.None, (int) data.index);
     }
     else if (this.m_ControlBuffer.Length == s_ControlDataIPv6Size)
     {
         UnsafeNclNativeMethods.OSSOCK.ControlDataIPv6 pv = (UnsafeNclNativeMethods.OSSOCK.ControlDataIPv6) Marshal.PtrToStructure(this.m_Message.controlBuffer.Pointer, typeof(UnsafeNclNativeMethods.OSSOCK.ControlDataIPv6));
         if (pv.length != UIntPtr.Zero)
         {
             address = new IPAddress(pv.address);
         }
         this.m_IPPacketInformation = new IPPacketInformation((address != null) ? address : IPAddress.IPv6None, (int) pv.index);
     }
     else
     {
         this.m_IPPacketInformation = new IPPacketInformation();
     }
 }
        public void CompletionCallback(int numBytes, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
        {
            Debug.Assert(_socketAddress != null);
            Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress);

            _socketAddressSize = socketAddressSize;
            _socketFlags = receivedFlags;
            _ipPacketInformation = ipPacketInformation;

            base.CompletionCallback(numBytes, errorCode);
        }
Beispiel #3
0
        public static NetworkInterface GetInterface(IPPacketInformation packetInfo)
        {
            int interfaceId = packetInfo.Interface;

            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (var netInterface in interfaces)
            {
                var ipv4InterfaceProps = netInterface.GetIPProperties().GetIPv4Properties();

                if (ipv4InterfaceProps != null &&
                    ipv4InterfaceProps.Index == interfaceId)
                    return netInterface;
            }

            return null;
        }
Beispiel #4
0
		public int EndReceiveMessageFrom (IAsyncResult asyncResult,
						  ref SocketFlags socketFlags,
						  ref EndPoint endPoint,
						  out IPPacketInformation ipPacketInformation)
		{
			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

			if (asyncResult == null)
				throw new ArgumentNullException ("asyncResult");

			if (endPoint == null)
				throw new ArgumentNullException ("endPoint");

			SocketAsyncResult req = asyncResult as SocketAsyncResult;
			if (req == null)
				throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");

			if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
				throw InvalidAsyncOp ("EndReceiveMessageFrom");
			throw new NotImplementedException ();
		}
Beispiel #5
0
        public static SocketError ReceiveMessageFrom(Socket socket, SafeCloseSocket handle, byte[] buffer, int offset, int count, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
        {
            byte[] socketAddressBuffer = socketAddress.Buffer;
            int socketAddressLen = socketAddress.Size;

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

            SocketError errorCode;
            if (!handle.IsNonBlocking)
            {
                errorCode = handle.AsyncContext.ReceiveMessageFrom(buffer, offset, count, ref socketFlags, socketAddressBuffer, ref socketAddressLen, isIPv4, isIPv6, handle.ReceiveTimeout, out ipPacketInformation, out bytesTransferred);
            }
            else
            {
                if (!TryCompleteReceiveMessageFrom(handle.FileDescriptor, buffer, offset, count, socketFlags, socketAddressBuffer, ref socketAddressLen, isIPv4, isIPv6, out bytesTransferred, out socketFlags, out ipPacketInformation, out errorCode))
                {
                    errorCode = SocketError.WouldBlock;
                }
            }

            socketAddress.InternalSize = socketAddressLen;
            receiveAddress = socketAddress;
            return errorCode;
        }
Beispiel #6
0
        private static unsafe int ReceiveMessageFrom(int fd, SocketFlags flags, int available, byte[] buffer, int offset, int count, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out Interop.Error errno)
        {
            Debug.Assert(socketAddress != null);

            int cmsgBufferLen = Interop.Sys.GetControlMessageBufferSize(isIPv4, isIPv6);
            var cmsgBuffer = stackalloc byte[cmsgBufferLen];

            int sockAddrLen = socketAddressLen;

            Interop.Sys.MessageHeader messageHeader;

            long received;
            fixed (byte* rawSocketAddress = socketAddress)
            fixed (byte* b = buffer)
            {
                var sockAddr = (byte*)rawSocketAddress;

                var iov = new Interop.Sys.IOVector {
                    Base = &b[offset],
                    Count = (UIntPtr)count
                };

                messageHeader = new Interop.Sys.MessageHeader {
                    SocketAddress = sockAddr,
                    SocketAddressLen = sockAddrLen,
                    IOVectors = &iov,
                    IOVectorCount = 1,
                    ControlBuffer = cmsgBuffer,
                    ControlBufferLen = cmsgBufferLen
                };

                errno = Interop.Sys.ReceiveMessage(fd, &messageHeader, flags, &received);
                receivedFlags = messageHeader.Flags;
                sockAddrLen = messageHeader.SocketAddressLen;
            }

            ipPacketInformation = GetIPPacketInformation(&messageHeader, isIPv4, isIPv6);

            if (errno != Interop.Error.SUCCESS)
            {
                return -1;
            }

            socketAddressLen = sockAddrLen;
            return checked((int)received);
        }
Beispiel #7
0
        internal void FinishOperationSuccess(SocketError socketError, int bytesTransferred, SocketFlags flags) {

            SetResults(socketError, bytesTransferred, flags);

            switch(m_CompletedOperation) {
                
                case SocketAsyncOperation.Accept:


                    if (bytesTransferred > 0) {
                        // Log and Perf counters.
                        if (s_LoggingEnabled) LogBuffer(bytesTransferred);
                        if (Socket.s_PerfCountersEnabled) UpdatePerfCounters(bytesTransferred, false);
                    }

                    // Get the endpoint.
                    SocketAddress remoteSocketAddress = m_CurrentSocket.m_RightEndPoint.Serialize();

                    IntPtr localAddr;
                    int localAddrLength;
                    IntPtr remoteAddr;

                    try {
                        m_CurrentSocket.GetAcceptExSockaddrs(
                            m_PtrSingleBuffer != IntPtr.Zero ? m_PtrSingleBuffer : m_PtrAcceptBuffer,
                            m_Count != 0 ? m_Count - m_AcceptAddressBufferCount : 0,
                            m_AcceptAddressBufferCount / 2,
                            m_AcceptAddressBufferCount / 2,
                            out localAddr,
                            out localAddrLength,
                            out remoteAddr,
                            out remoteSocketAddress.m_Size
                            );
                        Marshal.Copy(remoteAddr, remoteSocketAddress.m_Buffer, 0, remoteSocketAddress.m_Size);

                        // Set the socket context.
                        IntPtr handle = m_CurrentSocket.SafeHandle.DangerousGetHandle();

                        socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(
                            m_AcceptSocket.SafeHandle,
                            SocketOptionLevel.Socket,
                            SocketOptionName.UpdateAcceptContext,
                            ref handle,
                            Marshal.SizeOf(handle));

                        if(socketError == SocketError.SocketError) {
                            socketError = (SocketError)Marshal.GetLastWin32Error();
                        }
                    }
                    catch(ObjectDisposedException) {
                        socketError = SocketError.OperationAborted;
                    }

                    if(socketError == SocketError.Success) {
                        m_AcceptSocket = m_CurrentSocket.UpdateAcceptSocket(m_AcceptSocket, m_CurrentSocket.m_RightEndPoint.Create(remoteSocketAddress), false);

                        if (s_LoggingEnabled) Logging.PrintInfo(Logging.Sockets, m_AcceptSocket, 
                            SR.GetString(SR.net_log_socket_accepted, m_AcceptSocket.RemoteEndPoint, m_AcceptSocket.LocalEndPoint));
                    } else {
                        SetResults(socketError, bytesTransferred, SocketFlags.None);
                        m_AcceptSocket = null;
                    }
                    break;

                case SocketAsyncOperation.Connect:

                    if (bytesTransferred > 0) {
                        // Log and Perf counters.
                        if (s_LoggingEnabled) LogBuffer(bytesTransferred);
                        if (Socket.s_PerfCountersEnabled) UpdatePerfCounters(bytesTransferred, true);
                    }

                    // Update the socket context.
                    try {
                        socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(
                            m_CurrentSocket.SafeHandle,
                            SocketOptionLevel.Socket,
                            SocketOptionName.UpdateConnectContext,
                            null,
                            0);
                        if(socketError == SocketError.SocketError) {
                            socketError = (SocketError)Marshal.GetLastWin32Error();
                        }
                    }
                    catch(ObjectDisposedException) {
                        socketError = SocketError.OperationAborted;
                    }

                    // Mark socket connected.
                    if(socketError == SocketError.Success) {
                        if (s_LoggingEnabled) Logging.PrintInfo(Logging.Sockets, m_CurrentSocket, 
                            SR.GetString(SR.net_log_socket_connected, m_CurrentSocket.LocalEndPoint, m_CurrentSocket.RemoteEndPoint));

                        m_CurrentSocket.SetToConnected();
                        m_ConnectSocket = m_CurrentSocket;
                    }
                    break;

                case SocketAsyncOperation.Disconnect:

                    m_CurrentSocket.SetToDisconnected();
                    m_CurrentSocket.m_RemoteEndPoint = null;

                    break;

                case SocketAsyncOperation.Receive:

                    if (bytesTransferred > 0) {
                        // Log and Perf counters.
                        if (s_LoggingEnabled) LogBuffer(bytesTransferred);
                        if (Socket.s_PerfCountersEnabled) UpdatePerfCounters(bytesTransferred, false);
                    }
                    break;

                case SocketAsyncOperation.ReceiveFrom:

                    if (bytesTransferred > 0) {
                        // Log and Perf counters.
                        if (s_LoggingEnabled) LogBuffer(bytesTransferred);
                        if (Socket.s_PerfCountersEnabled) UpdatePerfCounters(bytesTransferred, false);
                    }

                    // Deal with incoming address.
                    m_SocketAddress.SetSize(m_PtrSocketAddressBufferSize);
                    SocketAddress socketAddressOriginal = m_RemoteEndPoint.Serialize();
                    if(!socketAddressOriginal.Equals(m_SocketAddress)) {
                        try {
                            m_RemoteEndPoint = m_RemoteEndPoint.Create(m_SocketAddress);
                        }
                        catch {
                        }
                    }
                    break;

                case SocketAsyncOperation.ReceiveMessageFrom:

                    if (bytesTransferred > 0) {
                        // Log and Perf counters.
                        if (s_LoggingEnabled) LogBuffer(bytesTransferred);
                        if (Socket.s_PerfCountersEnabled) UpdatePerfCounters(bytesTransferred, false);
                    }

                    // Deal with incoming address.
                    m_SocketAddress.SetSize(m_PtrSocketAddressBufferSize);
                    socketAddressOriginal = m_RemoteEndPoint.Serialize();
                    if(!socketAddressOriginal.Equals(m_SocketAddress)) {
                        try {
                            m_RemoteEndPoint = m_RemoteEndPoint.Create(m_SocketAddress);
                        }
                        catch {
                        }
                    }

                    // Extract the packet information.
                    unsafe {
                        IPAddress address = null;
                        UnsafeNclNativeMethods.OSSOCK.WSAMsg* PtrMessage = (UnsafeNclNativeMethods.OSSOCK.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(m_WSAMessageBuffer, 0);

                        //ipv4
                        if(m_ControlBuffer.Length == s_ControlDataSize) {
                            UnsafeNclNativeMethods.OSSOCK.ControlData controlData = (UnsafeNclNativeMethods.OSSOCK.ControlData)Marshal.PtrToStructure(PtrMessage->controlBuffer.Pointer, typeof(UnsafeNclNativeMethods.OSSOCK.ControlData));
                            if(controlData.length != UIntPtr.Zero) {
                                address = new IPAddress((long)controlData.address);
                            }
                            m_ReceiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.None), (int)controlData.index);
                        }
                            //ipv6
                        else if(m_ControlBuffer.Length == s_ControlDataIPv6Size) {
                            UnsafeNclNativeMethods.OSSOCK.ControlDataIPv6 controlData = (UnsafeNclNativeMethods.OSSOCK.ControlDataIPv6)Marshal.PtrToStructure(PtrMessage->controlBuffer.Pointer, typeof(UnsafeNclNativeMethods.OSSOCK.ControlDataIPv6));
                            if(controlData.length != UIntPtr.Zero) {
                                address = new IPAddress(controlData.address);
                            }
                            m_ReceiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.IPv6None), (int)controlData.index);
                        }
                            //other
                        else {
                            m_ReceiveMessageFromPacketInfo = new IPPacketInformation();
                        }
                    }
                    break;

                case SocketAsyncOperation.Send:

                    if (bytesTransferred > 0) {
                        // Log and Perf counters.
                        if (s_LoggingEnabled) LogBuffer(bytesTransferred);
                        if (Socket.s_PerfCountersEnabled) UpdatePerfCounters(bytesTransferred, true);
                    }
                    break;

                case SocketAsyncOperation.SendPackets:

                    if(bytesTransferred > 0) {
                        // Log and Perf counters.
                        if(s_LoggingEnabled) LogSendPacketsBuffers(bytesTransferred);
                        if(Socket.s_PerfCountersEnabled) UpdatePerfCounters(bytesTransferred, true);
                    }

                    // Close the files if open
                    if (m_SendPacketsFileStreams != null) {
                        for(int i = 0; i < m_SendPacketsElementsFileCount; i++) {
                            // Dereference handles
                            m_SendPacketsFileHandles[i] = null;
                            // Close any open streams
                            if(m_SendPacketsFileStreams[i] != null) {
                                m_SendPacketsFileStreams[i].Close();
                                m_SendPacketsFileStreams[i] = null;
                            }
                        }
                    }
                    m_SendPacketsFileStreams = null;
                    m_SendPacketsFileHandles = null;

                    break;

                case SocketAsyncOperation.SendTo:

                    if (bytesTransferred > 0) {
                        // Log and Perf counters.
                        if (s_LoggingEnabled) LogBuffer(bytesTransferred);
                        if (Socket.s_PerfCountersEnabled) UpdatePerfCounters(bytesTransferred, true);
                    }
                    break;

            }

            if(socketError != SocketError.Success) {
                // Asynchronous failure or something went wrong after async success.
                SetResults(socketError, bytesTransferred, flags);
                m_CurrentSocket.UpdateStatusAfterSocketError(socketError);
            }

            // Complete the operation and raise completion event.
            Complete();
            if(m_ContextCopy == null) {
                OnCompleted(this);
            } else {
                ExecutionContext.Run(m_ContextCopy, m_ExecutionCallback, null);
            }
        }
Beispiel #8
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;
        }
        public int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref System.Net.EndPoint endPoint, out IPPacketInformation ipPacketInformation)
        {
            ipPacketInformation = default(IPPacketInformation);

            return(default(int));
        }
Beispiel #10
0
		public int ReceiveMessageFrom (byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

			if (remoteEP == null)
				throw new ArgumentNullException ("remoteEP");

			// FIXME: figure out how we get hold of the IPPacketInformation
			throw new NotImplementedException ();
		}
        /// <summary>
        /// Extends ReceiveMessageFrom so that buffer offset of 0 and call to Array.Length are not needed.
        /// <example>
        /// socket.ReceiveMessageFrom(buffer, socketFlags, remoteEP, ipPacketInformation);
        /// </example>
        /// </summary>
        public static Int32 ReceiveMessageFrom(this Socket socket, Byte[] buffer, ref SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
        {
            if(socket == null) throw new ArgumentNullException("socket");

            if(buffer == null) throw new ArgumentNullException("buffer");

            return socket.ReceiveMessageFrom(buffer, 0, buffer.Length, ref socketFlags, ref remoteEP, out ipPacketInformation);
        }
        private void CompleteReceiveMessageFromOperation(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
        {
            Debug.Assert(_socketAddress != null, "Expected non-null _socketAddress");
            Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress, $"Unexpected socketAddress: {socketAddress}");

            _socketAddressSize            = socketAddressSize;
            _receivedFlags                = receivedFlags;
            _receiveMessageFromPacketInfo = ipPacketInformation;
        }
        private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
        {
            CompleteReceiveMessageFromOperation(bytesTransferred, socketAddress, socketAddressSize, receivedFlags, ipPacketInformation, errorCode);

            CompletionCallback(bytesTransferred, receivedFlags, errorCode);
        }
Beispiel #14
0
 public static unsafe SocketError ReceiveMessageFrom(Socket socket, SafeSocketHandle handle, byte[] buffer, int offset, int size, ref SocketFlags socketFlags, Internals.SocketAddress socketAddress, out Internals.SocketAddress receiveAddress, out IPPacketInformation ipPacketInformation, out int bytesTransferred)
 {
     return(ReceiveMessageFrom(socket, handle, new Span <byte>(buffer, offset, size), ref socketFlags, socketAddress, out receiveAddress, out ipPacketInformation, out bytesTransferred));
 }
Beispiel #15
0
        private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
        {
            Debug.Assert(_socketAddress != null);
            Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress);

            _socketAddressSize            = socketAddressSize;
            _receivedFlags                = receivedFlags;
            _receiveMessageFromPacketInfo = ipPacketInformation;

            CompletionCallback(bytesTransferred, errorCode);
        }
        public void CompletionCallback(int numBytes, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
        {
            Debug.Assert(_socketAddress != null, "_socketAddress was null");
            Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress, $"Unexpected socketAddress: {socketAddress}");

            _socketAddressSize   = socketAddressSize;
            _socketFlags         = receivedFlags;
            _ipPacketInformation = ipPacketInformation;

            base.CompletionCallback(numBytes, errorCode);
        }
        public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
        {
            ipPacketInformation = default(IPPacketInformation);

            return(default(int));
        }
Beispiel #18
0
 int Utils.Wrappers.Interfaces.ISocket.EndReceiveMessageFrom(System.IAsyncResult asyncResult, ref SocketFlags socketFlags, ref System.Net.EndPoint endPoint, out System.Net.Sockets.IPPacketInformation ipPacketInformation)
 {
     return(InternalSocket.EndReceiveMessageFrom(asyncResult, ref socketFlags, ref endPoint, out ipPacketInformation));
 }
Beispiel #19
0
        // Receives a datagram into a specific location in the data buffer and stores
        // the end point.
        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.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);
            }

            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;
            Internals.SocketAddress socketAddress = SnapshotAndSerialize(ref endPointSnapshot);

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

            SetReceivingPacketInformation();

            Internals.SocketAddress receiveAddress;
            int bytesTransferred;
            SocketError errorCode = SocketPal.ReceiveMessageFrom(this, _handle, buffer, offset, size, ref socketFlags, socketAddress, out receiveAddress, out ipPacketInformation, out bytesTransferred);

            // Throw an appropriate SocketException if the native call fails.
            if (errorCode != SocketError.Success && errorCode != SocketError.MessageSize)
            {
                // Update the internal state of this socket according to the error before throwing.
                SocketException socketException = new SocketException((int)errorCode);
                UpdateStatusAfterSocketError(socketException);
                if (s_loggingEnabled)
                {
                    Logging.Exception(Logging.Sockets, this, "ReceiveMessageFrom", socketException);
                }
                throw socketException;
            }

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

            if (s_loggingEnabled)
            {
                Logging.Exit(Logging.Sockets, this, "ReceiveMessageFrom", errorCode);
            }
            return bytesTransferred;
        }
Beispiel #20
0
 //
 // Summary:
 //     Ends a pending asynchronous read from a specific endpoint. This method also reveals
 //     more information about the packet than System.Net.Sockets.Socket.EndReceiveFrom(System.IAsyncResult,System.Net.EndPoint@).
 //
 // Parameters:
 //   asyncResult:
 //     An System.IAsyncResult that stores state information and any user defined data
 //     for this asynchronous operation.
 //
 //   socketFlags:
 //     A bitwise combination of the System.Net.Sockets.SocketFlags values for the received
 //     packet.
 //
 //   endPoint:
 //     The source System.Net.EndPoint.
 //
 //   ipPacketInformation:
 //     The System.Net.IPAddress and interface of the received packet.
 //
 // Returns:
 //     If successful, the number of bytes received. If unsuccessful, returns 0.
 //
 // Exceptions:
 //   T:System.ArgumentNullException:
 //     asyncResult is null-or- endPoint is null.
 //
 //   T:System.ArgumentException:
 //     asyncResult was not returned by a call to the System.Net.Sockets.Socket.BeginReceiveMessageFrom(System.Byte[],System.Int32,System.Int32,System.Net.Sockets.SocketFlags,System.Net.EndPoint@,System.AsyncCallback,System.Object)
 //     method.
 //
 //   T:System.InvalidOperationException:
 //     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.
 //
 //   T:System.Net.Sockets.SocketException:
 //     An error occurred when attempting to access the socket. See the Remarks section
 //     for more information.
 //
 //   T:System.ObjectDisposedException:
 //     The System.Net.Sockets.Socket has been closed.
 public static int EndReceiveMessageFrom(this Socket socket, IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
 {
     SocketReceiveMessageFromResult result = TaskToApm.End<SocketReceiveMessageFromResult>(asyncResult);
     socketFlags = result.SocketFlags;
     endPoint = result.RemoteEndPoint;
     ipPacketInformation = result.PacketInformation;
     return result.ReceivedBytes;
 }
        unsafe private void InitIPPacketInformation()
        {
            IPAddress address = null;

            if (_controlBuffer.Length == s_controlDataSize)
            {
                // IPv4
                Interop.Winsock.ControlData controlData = Marshal.PtrToStructure<Interop.Winsock.ControlData>(_message->controlBuffer.Pointer);
                if (controlData.length != UIntPtr.Zero)
                {
                    address = new IPAddress((long)controlData.address);
                }

                _ipPacketInformation = new IPPacketInformation(((address != null) ? address : IPAddress.None), (int)controlData.index);
            }
            else if (_controlBuffer.Length == s_controlDataIPv6Size)
            {
                // IPv6
                Interop.Winsock.ControlDataIPv6 controlData = Marshal.PtrToStructure<Interop.Winsock.ControlDataIPv6>(_message->controlBuffer.Pointer);
                if (controlData.length != UIntPtr.Zero)
                {
                    address = new IPAddress(controlData.address);
                }

                _ipPacketInformation = new IPPacketInformation(((address != null) ? address : IPAddress.IPv6None), (int)controlData.index);
            }
            else
            {
                // Other
                _ipPacketInformation = new IPPacketInformation();
            }
        }
    public int ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
    {
      ipPacketInformation = default(IPPacketInformation);

      return default(int);
    }
        internal unsafe void FinishOperationSuccess(System.Net.Sockets.SocketError socketError, int bytesTransferred, System.Net.Sockets.SocketFlags flags)
        {
            this.SetResults(socketError, bytesTransferred, flags);
            switch (this.m_CompletedOperation)
            {
                case SocketAsyncOperation.Accept:
                {
                    if (bytesTransferred > 0)
                    {
                        if (s_LoggingEnabled)
                        {
                            this.LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_PerfCountersEnabled)
                        {
                            this.UpdatePerfCounters(bytesTransferred, false);
                        }
                    }
                    SocketAddress socketAddress = this.m_CurrentSocket.m_RightEndPoint.Serialize();
                    try
                    {
                        IntPtr ptr;
                        int num;
                        IntPtr ptr2;
                        this.m_CurrentSocket.GetAcceptExSockaddrs((this.m_PtrSingleBuffer != IntPtr.Zero) ? this.m_PtrSingleBuffer : this.m_PtrAcceptBuffer, (this.m_Count != 0) ? (this.m_Count - this.m_AcceptAddressBufferCount) : 0, this.m_AcceptAddressBufferCount / 2, this.m_AcceptAddressBufferCount / 2, out ptr, out num, out ptr2, out socketAddress.m_Size);
                        Marshal.Copy(ptr2, socketAddress.m_Buffer, 0, socketAddress.m_Size);
                        IntPtr handle = this.m_CurrentSocket.SafeHandle.DangerousGetHandle();
                        socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(this.m_AcceptSocket.SafeHandle, SocketOptionLevel.Socket, SocketOptionName.UpdateAcceptContext, ref handle, Marshal.SizeOf(handle));
                        if (socketError == System.Net.Sockets.SocketError.SocketError)
                        {
                            socketError = (System.Net.Sockets.SocketError) Marshal.GetLastWin32Error();
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        socketError = System.Net.Sockets.SocketError.OperationAborted;
                    }
                    if (socketError == System.Net.Sockets.SocketError.Success)
                    {
                        this.m_AcceptSocket = this.m_CurrentSocket.UpdateAcceptSocket(this.m_AcceptSocket, this.m_CurrentSocket.m_RightEndPoint.Create(socketAddress), false);
                        if (s_LoggingEnabled)
                        {
                            Logging.PrintInfo(Logging.Sockets, this.m_AcceptSocket, SR.GetString("net_log_socket_accepted", new object[] { this.m_AcceptSocket.RemoteEndPoint, this.m_AcceptSocket.LocalEndPoint }));
                        }
                    }
                    else
                    {
                        this.SetResults(socketError, bytesTransferred, System.Net.Sockets.SocketFlags.None);
                        this.m_AcceptSocket = null;
                    }
                    break;
                }
                case SocketAsyncOperation.Connect:
                    if (bytesTransferred > 0)
                    {
                        if (s_LoggingEnabled)
                        {
                            this.LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_PerfCountersEnabled)
                        {
                            this.UpdatePerfCounters(bytesTransferred, true);
                        }
                    }
                    try
                    {
                        socketError = UnsafeNclNativeMethods.OSSOCK.setsockopt(this.m_CurrentSocket.SafeHandle, SocketOptionLevel.Socket, SocketOptionName.UpdateConnectContext, (byte[]) null, 0);
                        if (socketError == System.Net.Sockets.SocketError.SocketError)
                        {
                            socketError = (System.Net.Sockets.SocketError) Marshal.GetLastWin32Error();
                        }
                    }
                    catch (ObjectDisposedException)
                    {
                        socketError = System.Net.Sockets.SocketError.OperationAborted;
                    }
                    if (socketError == System.Net.Sockets.SocketError.Success)
                    {
                        if (s_LoggingEnabled)
                        {
                            Logging.PrintInfo(Logging.Sockets, this.m_CurrentSocket, SR.GetString("net_log_socket_connected", new object[] { this.m_CurrentSocket.LocalEndPoint, this.m_CurrentSocket.RemoteEndPoint }));
                        }
                        this.m_CurrentSocket.SetToConnected();
                        this.m_ConnectSocket = this.m_CurrentSocket;
                    }
                    break;

                case SocketAsyncOperation.Disconnect:
                    this.m_CurrentSocket.SetToDisconnected();
                    this.m_CurrentSocket.m_RemoteEndPoint = null;
                    break;

                case SocketAsyncOperation.Receive:
                    if (bytesTransferred > 0)
                    {
                        if (s_LoggingEnabled)
                        {
                            this.LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_PerfCountersEnabled)
                        {
                            this.UpdatePerfCounters(bytesTransferred, false);
                        }
                    }
                    break;

                case SocketAsyncOperation.ReceiveFrom:
                    if (bytesTransferred > 0)
                    {
                        if (s_LoggingEnabled)
                        {
                            this.LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_PerfCountersEnabled)
                        {
                            this.UpdatePerfCounters(bytesTransferred, false);
                        }
                    }
                    this.m_SocketAddress.SetSize(this.m_PtrSocketAddressBufferSize);
                    if (!this.m_RemoteEndPoint.Serialize().Equals(this.m_SocketAddress))
                    {
                        try
                        {
                            this.m_RemoteEndPoint = this.m_RemoteEndPoint.Create(this.m_SocketAddress);
                        }
                        catch
                        {
                        }
                    }
                    break;

                case SocketAsyncOperation.ReceiveMessageFrom:
                {
                    if (bytesTransferred > 0)
                    {
                        if (s_LoggingEnabled)
                        {
                            this.LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_PerfCountersEnabled)
                        {
                            this.UpdatePerfCounters(bytesTransferred, false);
                        }
                    }
                    this.m_SocketAddress.SetSize(this.m_PtrSocketAddressBufferSize);
                    if (!this.m_RemoteEndPoint.Serialize().Equals(this.m_SocketAddress))
                    {
                        try
                        {
                            this.m_RemoteEndPoint = this.m_RemoteEndPoint.Create(this.m_SocketAddress);
                        }
                        catch
                        {
                        }
                    }
                    IPAddress address3 = null;
                    UnsafeNclNativeMethods.OSSOCK.WSAMsg* msgPtr = (UnsafeNclNativeMethods.OSSOCK.WSAMsg*) Marshal.UnsafeAddrOfPinnedArrayElement(this.m_WSAMessageBuffer, 0);
                    if (this.m_ControlBuffer.Length == s_ControlDataSize)
                    {
                        UnsafeNclNativeMethods.OSSOCK.ControlData data = (UnsafeNclNativeMethods.OSSOCK.ControlData) Marshal.PtrToStructure(msgPtr->controlBuffer.Pointer, typeof(UnsafeNclNativeMethods.OSSOCK.ControlData));
                        if (data.length != UIntPtr.Zero)
                        {
                            address3 = new IPAddress((long) data.address);
                        }
                        this.m_ReceiveMessageFromPacketInfo = new IPPacketInformation((address3 != null) ? address3 : IPAddress.None, (int) data.index);
                    }
                    else if (this.m_ControlBuffer.Length == s_ControlDataIPv6Size)
                    {
                        UnsafeNclNativeMethods.OSSOCK.ControlDataIPv6 pv = (UnsafeNclNativeMethods.OSSOCK.ControlDataIPv6) Marshal.PtrToStructure(msgPtr->controlBuffer.Pointer, typeof(UnsafeNclNativeMethods.OSSOCK.ControlDataIPv6));
                        if (pv.length != UIntPtr.Zero)
                        {
                            address3 = new IPAddress(pv.address);
                        }
                        this.m_ReceiveMessageFromPacketInfo = new IPPacketInformation((address3 != null) ? address3 : IPAddress.IPv6None, (int) pv.index);
                    }
                    else
                    {
                        this.m_ReceiveMessageFromPacketInfo = new IPPacketInformation();
                    }
                    break;
                }
                case SocketAsyncOperation.Send:
                    if (bytesTransferred > 0)
                    {
                        if (s_LoggingEnabled)
                        {
                            this.LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_PerfCountersEnabled)
                        {
                            this.UpdatePerfCounters(bytesTransferred, true);
                        }
                    }
                    break;

                case SocketAsyncOperation.SendPackets:
                    if (bytesTransferred > 0)
                    {
                        if (s_LoggingEnabled)
                        {
                            this.LogSendPacketsBuffers(bytesTransferred);
                        }
                        if (Socket.s_PerfCountersEnabled)
                        {
                            this.UpdatePerfCounters(bytesTransferred, true);
                        }
                    }
                    if (this.m_SendPacketsFileStreams != null)
                    {
                        for (int i = 0; i < this.m_SendPacketsElementsFileCount; i++)
                        {
                            this.m_SendPacketsFileHandles[i] = null;
                            if (this.m_SendPacketsFileStreams[i] != null)
                            {
                                this.m_SendPacketsFileStreams[i].Close();
                                this.m_SendPacketsFileStreams[i] = null;
                            }
                        }
                    }
                    this.m_SendPacketsFileStreams = null;
                    this.m_SendPacketsFileHandles = null;
                    break;

                case SocketAsyncOperation.SendTo:
                    if (bytesTransferred > 0)
                    {
                        if (s_LoggingEnabled)
                        {
                            this.LogBuffer(bytesTransferred);
                        }
                        if (Socket.s_PerfCountersEnabled)
                        {
                            this.UpdatePerfCounters(bytesTransferred, true);
                        }
                    }
                    break;
            }
            if (socketError != System.Net.Sockets.SocketError.Success)
            {
                this.SetResults(socketError, bytesTransferred, flags);
                this.m_CurrentSocket.UpdateStatusAfterSocketError(socketError);
            }
            this.Complete();
            if (this.m_ContextCopy == null)
            {
                this.OnCompleted(this);
            }
            else
            {
                ExecutionContext.Run(this.m_ContextCopy, this.m_ExecutionCallback, null);
            }
        }
Beispiel #24
0
        public static unsafe 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)
        {
            bool ipv4, ipv6;

            Socket.GetIPProtocolInformation(socket.AddressFamily, socketAddress, out ipv4, out ipv6);

            bytesTransferred    = 0;
            receiveAddress      = socketAddress;
            ipPacketInformation = default(IPPacketInformation);

            fixed(byte *ptrBuffer = buffer)
            fixed(byte *ptrSocketAddress = socketAddress.Buffer)
            {
                Interop.Winsock.WSAMsg wsaMsg;
                wsaMsg.socketAddress = (IntPtr)ptrSocketAddress;
                wsaMsg.addressLength = (uint)socketAddress.Size;
                wsaMsg.flags         = socketFlags;

                WSABuffer wsaBuffer;

                wsaBuffer.Length  = size;
                wsaBuffer.Pointer = (IntPtr)(ptrBuffer + offset);
                wsaMsg.buffers    = (IntPtr)(&wsaBuffer);
                wsaMsg.count      = 1;

                if (ipv4)
                {
                    Interop.Winsock.ControlData controlBuffer;
                    wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
                    wsaMsg.controlBuffer.Length  = sizeof(Interop.Winsock.ControlData);

                    if (socket.WSARecvMsgBlocking(
                            handle.DangerousGetHandle(),
                            (IntPtr)(&wsaMsg),
                            out bytesTransferred,
                            IntPtr.Zero,
                            IntPtr.Zero) == SocketError.SocketError)
                    {
                        return(GetLastSocketError());
                    }

                    ipPacketInformation = GetIPPacketInformation(&controlBuffer);
                }
                else if (ipv6)
                {
                    Interop.Winsock.ControlDataIPv6 controlBuffer;
                    wsaMsg.controlBuffer.Pointer = (IntPtr)(&controlBuffer);
                    wsaMsg.controlBuffer.Length  = sizeof(Interop.Winsock.ControlDataIPv6);

                    if (socket.WSARecvMsgBlocking(
                            handle.DangerousGetHandle(),
                            (IntPtr)(&wsaMsg),
                            out bytesTransferred,
                            IntPtr.Zero,
                            IntPtr.Zero) == SocketError.SocketError)
                    {
                        return(GetLastSocketError());
                    }

                    ipPacketInformation = GetIPPacketInformation(&controlBuffer);
                }
                else
                {
                    wsaMsg.controlBuffer.Pointer = IntPtr.Zero;
                    wsaMsg.controlBuffer.Length  = 0;

                    if (socket.WSARecvMsgBlocking(
                            handle.DangerousGetHandle(),
                            (IntPtr)(&wsaMsg),
                            out bytesTransferred,
                            IntPtr.Zero,
                            IntPtr.Zero) == SocketError.SocketError)
                    {
                        return(GetLastSocketError());
                    }
                }

                socketFlags = wsaMsg.flags;
            }

            return(SocketError.Success);
        }
Beispiel #25
0
        public static unsafe bool TryCompleteReceiveMessageFrom(SafeCloseSocket socket, byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out SocketError errorCode)
        {
            try
            {
                Interop.Error errno;

                int received = ReceiveMessageFrom(socket, flags, buffer, offset, count, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out receivedFlags, out ipPacketInformation, out errno);

                if (received != -1)
                {
                    bytesReceived = received;
                    errorCode = SocketError.Success;
                    return true;
                }

                bytesReceived = 0;

                if (errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
                {
                    errorCode = GetSocketErrorForErrorCode(errno);
                    return true;
                }

                errorCode = SocketError.Success;
                return false;
            }
            catch (ObjectDisposedException)
            {
                // The socket was closed, or is closing.
                bytesReceived = 0;
                receivedFlags = 0;
                ipPacketInformation = default(IPPacketInformation);
                errorCode = SocketError.OperationAborted;
                return true;
            }
        }
Beispiel #26
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);
        }
Beispiel #27
0
        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 (CleanedUp) {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            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");
            }
            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"));
            }

            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) + "::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(s_LoggingEnabled)Logging.Exception(Logging.Sockets, this, "EndReceiveMessageFrom", socketException);
                throw socketException;
            }

            socketFlags = castedAsyncResult.m_flags;
            ipPacketInformation = castedAsyncResult.m_IPPacketInformation;

            if(s_LoggingEnabled)Logging.Exit(Logging.Sockets, this, "EndReceiveMessageFrom", bytesTransferred);
            return bytesTransferred;
        }
Beispiel #28
0
        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;
        }
Beispiel #29
0
        private static unsafe int ReceiveMessageFrom(int fd, int flags, int available, byte[] buffer, int offset, int count, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int receivedFlags, out IPPacketInformation ipPacketInformation, out Interop.Error errno)
        {
            Debug.Assert(socketAddress != null);

            int cmsgBufferLen =
                (isIPv4 ? AlignControlMessageSize(sizeof(Interop.libc.cmsghdr) + sizeof(Interop.libc.in_pktinfo)) : 0) +
                (isIPv6 ? AlignControlMessageSize(sizeof(Interop.libc.cmsghdr) + sizeof(Interop.libc.in6_pktinfo)) : 0);
            var cmsgBuffer = stackalloc byte[cmsgBufferLen];

            var sockAddrLen = (uint)socketAddressLen;

            int received;
            fixed (byte* rawSocketAddress = socketAddress)
            fixed (byte* b = buffer)
            {
                var sockAddr = (Interop.libc.sockaddr*)rawSocketAddress;

                var iov = new Interop.libc.iovec {
                    iov_base = &b[offset],
                    iov_len = (IntPtr)count
                };

                var msghdr = new Interop.libc.msghdr(sockAddr, sockAddrLen, &iov, 1, cmsgBuffer, cmsgBufferLen, 0);
                received = (int)Interop.libc.recvmsg(fd, &msghdr, flags);
                receivedFlags = msghdr.msg_flags;
                sockAddrLen = msghdr.msg_namelen;
                cmsgBufferLen = (int)msghdr.msg_controllen;
            }

            ipPacketInformation = GetIPPacketInformation(cmsgBuffer, cmsgBufferLen, isIPv4, isIPv6);

            if (received == -1)
            {
                errno = Interop.Sys.GetLastError();
                return -1;
            }

            socketAddressLen = (int)sockAddrLen;
            errno = Interop.Error.SUCCESS;
            return received;
        }
Beispiel #30
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;
        }
Beispiel #31
0
        public static unsafe bool TryCompleteReceiveMessageFrom(int fileDescriptor, byte[] buffer, int offset, int count, SocketFlags flags, byte[] socketAddress, ref int socketAddressLen, bool isIPv4, bool isIPv6, out int bytesReceived, out SocketFlags receivedFlags, out IPPacketInformation ipPacketInformation, out SocketError errorCode)
        {
            int available;
            Interop.Error errno = Interop.Sys.GetBytesAvailable(fileDescriptor, &available);
            if (errno != Interop.Error.SUCCESS)
            {
                bytesReceived = 0;
                receivedFlags = 0;
                ipPacketInformation = default(IPPacketInformation);
                errorCode = GetSocketErrorForErrorCode(errno);
                return true;
            }
            if (available == 0)
            {
                // Always request at least one byte.
                available = 1;
            }

            int received = ReceiveMessageFrom(fileDescriptor, flags, available, buffer, offset, count, socketAddress, ref socketAddressLen, isIPv4, isIPv6, out receivedFlags, out ipPacketInformation, out errno);

            if (received != -1)
            {
                bytesReceived = received;
                errorCode = SocketError.Success;
                return true;
            }

            bytesReceived = 0;

            if (errno != Interop.Error.EAGAIN && errno != Interop.Error.EWOULDBLOCK)
            {
                errorCode = GetSocketErrorForErrorCode(errno);
                return true;
            }

            errorCode = SocketError.Success;
            return false;
        }
Beispiel #32
0
 /// <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;
       }
     }
       }
 }
        private unsafe void FinishOperationReceiveMessageFrom()
        {
            IPAddress address = null;
            Interop.Winsock.WSAMsg* PtrMessage = (Interop.Winsock.WSAMsg*)Marshal.UnsafeAddrOfPinnedArrayElement(_wsaMessageBuffer, 0);

            if (_controlBuffer.Length == s_controlDataSize)
            {
                // IPv4.
                Interop.Winsock.ControlData controlData = Marshal.PtrToStructure<Interop.Winsock.ControlData>(PtrMessage->controlBuffer.Pointer);
                if (controlData.length != UIntPtr.Zero)
                {
                    address = new IPAddress((long)controlData.address);
                }
                _receiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.None), (int)controlData.index);
            }
            else if (_controlBuffer.Length == s_controlDataIPv6Size)
            {
                // IPv6.
                Interop.Winsock.ControlDataIPv6 controlData = Marshal.PtrToStructure<Interop.Winsock.ControlDataIPv6>(PtrMessage->controlBuffer.Pointer);
                if (controlData.length != UIntPtr.Zero)
                {
                    address = new IPAddress(controlData.address);
                }
                _receiveMessageFromPacketInfo = new IPPacketInformation(((address != null) ? address : IPAddress.IPv6None), (int)controlData.index);
            }
            else
            {
                // Other.
                _receiveMessageFromPacketInfo = new IPPacketInformation();
            }
        }
Beispiel #34
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;
     }
       }
 }
Beispiel #35
0
		public int ReceiveMessageFrom (byte[] buffer, int offset,
					       int size,
					       ref SocketFlags socketFlags,
					       ref EndPoint remoteEP,
					       out IPPacketInformation ipPacketInformation)
		{
			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

			if (buffer == null)
				throw new ArgumentNullException ("buffer");

			if (remoteEP == null)
				throw new ArgumentNullException ("remoteEP");

			CheckRange (buffer, offset, size);

			/* FIXME: figure out how we get hold of the
			 * IPPacketInformation
			 */
			throw new NotImplementedException ();
		}
        private void ReceiveMessageFromCompletionCallback(int bytesTransferred, byte[] socketAddress, int socketAddressSize, SocketFlags receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
        {
            Debug.Assert(_socketAddress != null);
            Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress);

            _socketAddressSize = socketAddressSize;
            _receivedFlags = receivedFlags;
            _receiveMessageFromPacketInfo = ipPacketInformation;

            CompletionCallback(bytesTransferred, errorCode);
        }
Beispiel #37
0
 int Utils.Wrappers.Interfaces.ISocket.ReceiveMessageFrom(byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref System.Net.EndPoint remoteEP, out System.Net.Sockets.IPPacketInformation ipPacketInformation)
 {
     return(InternalSocket.ReceiveMessageFrom(buffer, offset, size, ref socketFlags, ref remoteEP, out ipPacketInformation));
 }
 public int EndReceiveMessageFrom(IAsyncResult result, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
 {
     return socket.EndReceiveMessageFrom(result, ref socketFlags, ref endPoint, out ipPacketInformation);
 }
Beispiel #39
0
        internal int EndReceiveMessageFrom(IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
        {
            if (s_loggingEnabled)
            {
                Logging.Enter(Logging.Sockets, this, "EndReceiveMessageFrom", asyncResult);
            }
            if (CleanedUp)
            {
                throw new ObjectDisposedException(this.GetType().FullName);
            }
            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");
            }

            ReceiveMessageOverlappedAsyncResult castedAsyncResult = asyncResult as ReceiveMessageOverlappedAsyncResult;
            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, "EndReceiveMessageFrom"));
            }

            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) + "::EndReceiveMessageFrom() bytesTransferred:" + bytesTransferred.ToString());

            // 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 (s_loggingEnabled)
                {
                    Logging.Exception(Logging.Sockets, this, "EndReceiveMessageFrom", socketException);
                }
                throw socketException;
            }

            socketFlags = castedAsyncResult.SocketFlags;
            ipPacketInformation = castedAsyncResult.IPPacketInformation;

            if (s_loggingEnabled)
            {
                Logging.Exit(Logging.Sockets, this, "EndReceiveMessageFrom", bytesTransferred);
            }
            return bytesTransferred;
        }
Beispiel #40
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;
        }
Beispiel #41
0
		public int EndReceiveMessageFrom (IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
		{
			ThrowIfDisposedAndClosed ();

			if (endPoint == null)
				throw new ArgumentNullException ("endPoint");

			SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndReceiveMessageFrom", "asyncResult");

			throw new NotImplementedException ();
		}
Beispiel #42
0
        public void CompletionCallback(int numBytes, byte[] socketAddress, int socketAddressSize, int receivedFlags, IPPacketInformation ipPacketInformation, SocketError errorCode)
        {
            Debug.Assert(_socketAddress != null);
            Debug.Assert(socketAddress == null || _socketAddress.Buffer == socketAddress);

            _socketAddressSize   = socketAddressSize;
            _socketFlags         = SocketPal.GetSocketFlags(receivedFlags);
            _ipPacketInformation = ipPacketInformation;

            base.CompletionCallback(numBytes, errorCode);
        }