internal static bool DoesEndPointUsePlatformProtocols(EndPoint endPoint)
 {
   if (endPoint.GetType().FullName == "UnityEngine.PS4.SceEndPoint")
   {
     SocketAddress socketAddress = endPoint.Serialize();
     if ((int) socketAddress[8] != 0 || (int) socketAddress[9] != 0)
       return true;
   }
   return false;
 }
예제 #2
0
        /// <inheritdoc/>
        public void Send(Byte[] data, System.Net.EndPoint ep)
        {
            RawData raw = new RawData();

            raw.Data     = data;
            raw.EndPoint = ep;
            _sendingQueue.Enqueue(raw);
            log.Info($"UDP-Enqueued {ep.Serialize()}({data?.Length})");
            if (System.Threading.Interlocked.CompareExchange(ref _writing, 1, 0) > 0)
            {
                return;
            }
            BeginSend();
        }
 public static int ConnectEndPoint(int hostId, EndPoint endPoint, int exceptionConnectionId, out byte error)
 {
   error = (byte) 0;
   byte[] numArray1 = new byte[4]{ (byte) 95, (byte) 36, (byte) 19, (byte) 246 };
   if (endPoint == null)
     throw new NullReferenceException("Null EndPoint provided");
   if (endPoint.GetType().FullName != "UnityEngine.XboxOne.XboxOneEndPoint" && endPoint.GetType().FullName != "UnityEngine.PS4.SceEndPoint")
     throw new ArgumentException("Endpoint of type XboxOneEndPoint or SceEndPoint  required");
   if (endPoint.GetType().FullName == "UnityEngine.XboxOne.XboxOneEndPoint")
   {
     EndPoint endPoint1 = endPoint;
     if (endPoint1.AddressFamily != AddressFamily.InterNetworkV6)
       throw new ArgumentException("XboxOneEndPoint has an invalid family");
     SocketAddress socketAddress = endPoint1.Serialize();
     if (socketAddress.Size != 14)
       throw new ArgumentException("XboxOneEndPoint has an invalid size");
     if ((int) socketAddress[0] != 0 || (int) socketAddress[1] != 0)
       throw new ArgumentException("XboxOneEndPoint has an invalid family signature");
     if ((int) socketAddress[2] != (int) numArray1[0] || (int) socketAddress[3] != (int) numArray1[1] || ((int) socketAddress[4] != (int) numArray1[2] || (int) socketAddress[5] != (int) numArray1[3]))
       throw new ArgumentException("XboxOneEndPoint has an invalid signature");
     byte[] numArray2 = new byte[8];
     for (int index = 0; index < numArray2.Length; ++index)
       numArray2[index] = socketAddress[6 + index];
     IntPtr num = new IntPtr(BitConverter.ToInt64(numArray2, 0));
     if (num == IntPtr.Zero)
       throw new ArgumentException("XboxOneEndPoint has an invalid SOCKET_STORAGE pointer");
     byte[] destination = new byte[2];
     Marshal.Copy(num, destination, 0, destination.Length);
     if (((int) destination[1] << 8) + (int) destination[0] != 23)
       throw new ArgumentException("XboxOneEndPoint has corrupt or invalid SOCKET_STORAGE pointer");
     return NetworkTransport.Internal_ConnectEndPoint(hostId, num, 128, exceptionConnectionId, out error);
   }
   SocketAddress socketAddress1 = endPoint.Serialize();
   if (socketAddress1.Size != 16)
     throw new ArgumentException("EndPoint has an invalid size");
   if ((int) socketAddress1[0] != socketAddress1.Size)
     throw new ArgumentException("EndPoint has an invalid size value");
   if ((int) socketAddress1[1] != 2)
     throw new ArgumentException("EndPoint has an invalid family value");
   byte[] source = new byte[16];
   for (int index = 0; index < source.Length; ++index)
     source[index] = socketAddress1[index];
   IntPtr num1 = Marshal.AllocHGlobal(source.Length);
   Marshal.Copy(source, 0, num1, source.Length);
   int num2 = NetworkTransport.Internal_ConnectEndPoint(hostId, num1, 16, exceptionConnectionId, out error);
   Marshal.FreeHGlobal(num1);
   return num2;
 }
예제 #4
0
		public IAsyncResult BeginConnect(EndPoint end_point,
						 AsyncCallback callback,
						 object state) {

			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

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

			SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
			req.EndPoint = end_point;

			// Bug #75154: Connect() should not succeed for .Any addresses.
			if (end_point is IPEndPoint) {
				IPEndPoint ep = (IPEndPoint) end_point;
				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
					req.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
					return req;
				}
			}

			int error = 0;
			if (!blocking) {
				SocketAddress serial = end_point.Serialize ();
				Connect_internal (socket, serial, out error);
				if (error == 0) {
					// succeeded synch
					connected = true;
					req.Complete (true);
				} else if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
					// error synch
					connected = false;
					req.Complete (new SocketException (error), true);
				}
			}

			if (blocking || error == (int) SocketError.InProgress || error == (int) SocketError.WouldBlock) {
				// continue asynch
				connected = false;
				Worker worker = new Worker (req);
				SocketAsyncCall sac = new SocketAsyncCall (worker.Connect);
				sac.BeginInvoke (null, req);
			}

			return(req);
		}
예제 #5
0
파일: Socket.cs 프로젝트: grendello/mono
		public int SendTo (byte [] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
		{
			ThrowIfDisposedAndClosed ();
			ThrowIfBufferNull (buffer);
			ThrowIfBufferOutOfRange (buffer, offset, size);

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

			int error;
			int ret = SendTo_internal (m_Handle, buffer, offset, size, socketFlags, remoteEP.Serialize (), out error, is_blocking);

			SocketError err = (SocketError) error;
			if (err != 0) {
				if (err != SocketError.WouldBlock && err != SocketError.InProgress)
					is_connected = false;
				throw new SocketException (error);
			}

			is_connected = true;
			is_bound = true;
			seed_endpoint = remoteEP;

			return ret;
		}
예제 #6
0
파일: Socket.cs 프로젝트: Profit0004/mono
		public void Connect (EndPoint remoteEP)
		{
			ThrowIfDisposedAndClosed ();

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

			IPEndPoint ep = remoteEP as IPEndPoint;
			/* Dgram uses Any to 'disconnect' */
			if (ep != null && socket_type != SocketType.Dgram) {
				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
					throw new SocketException ((int) SocketError.AddressNotAvailable);
			}

			if (is_listening)
				throw new InvalidOperationException ();

			SocketAddress serial = remoteEP.Serialize ();

			int error = 0;
			Connect_internal (safe_handle, serial, out error);

			if (error == 0 || error == 10035)
				seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets

			if (error != 0) {
				if (is_closed)
					error = SOCKET_CLOSED_CODE;
				throw new SocketException (error);
			}

			is_connected = !(socket_type == SocketType.Dgram && ep != null && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)));
			is_bound = true;
		}
예제 #7
0
파일: Socket.cs 프로젝트: frje/SharpLang
		public void Bind(EndPoint local_end) {
			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

			if (local_end == null)
				throw new ArgumentNullException("local_end");
			
			int error;
			
			Bind_internal(socket, local_end.Serialize(), out error);
			if (error != 0)
				throw new SocketException (error);
			if (error == 0)
				isbound = true;
			
			seed_endpoint = local_end;
		}
예제 #8
0
파일: Socket.cs 프로젝트: REALTOBIZ/mono
        // Give a nicer exception for DnsEndPoint in cases where it is not supported
        private SocketAddress CallSerializeCheckDnsEndPoint(EndPoint remoteEP)
        {
            if (remoteEP is DnsEndPoint)
            {
                throw new ArgumentException(SR.GetString(SR.net_sockets_invalid_dnsendpoint, "remoteEP"), "remoteEP");
            }

            return remoteEP.Serialize();
        }
예제 #9
0
파일: Socket.cs 프로젝트: REALTOBIZ/mono
        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;
        }
예제 #10
0
파일: Socket_2_1.cs 프로젝트: nlhepler/mono
		public void Connect (EndPoint remoteEP)
		{
			SocketAddress serial = null;

			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

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

			IPEndPoint ep = remoteEP as IPEndPoint;
			if (ep != null && socket_type != SocketType.Dgram) /* Dgram uses Any to 'disconnect' */
				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
					throw new SocketException ((int) SocketError.AddressNotAvailable);

			if (islistening)
				throw new InvalidOperationException ();
			serial = remoteEP.Serialize ();

			int error = 0;

			try {
				RegisterForBlockingSyscall ();
				Connect_internal (socket, serial, out error);
			} finally {
				UnRegisterForBlockingSyscall ();
			}

			if (error == 0 || error == 10035)
				seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets

			if (error != 0) {
				if (closed)
					error = SOCKET_CLOSED;
				throw new SocketException (error);
			}

			if (socket_type == SocketType.Dgram && ep != null && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)))
				connected = false;
			else
				connected = true;
			isbound = true;
		}
예제 #11
0
		public void Bind (EndPoint localEP)
		{
			ThrowIfDisposedAndClosed ();

			if (localEP == null)
				throw new ArgumentNullException("localEP");
				
			var ipEndPoint = localEP as IPEndPoint;
			if (ipEndPoint != null) {
				localEP = RemapIPEndPoint (ipEndPoint);	
			}
			
			int error;
			Bind_internal (safe_handle, localEP.Serialize(), out error);

			if (error != 0)
				throw new SocketException (error);
			if (error == 0)
				is_bound = true;

			seed_endpoint = localEP;
		}
예제 #12
0
		public void Connect (EndPoint remoteEP)
		{
			SocketAddress serial = null;

			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

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

			IPEndPoint ep = remoteEP as IPEndPoint;
			if (ep != null)
				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
					throw new SocketException ((int) SocketError.AddressNotAvailable);

#if MOONLIGHT
			if (protocol_type != ProtocolType.Tcp)
				throw new SocketException ((int) SocketError.AccessDenied);
#elif NET_2_0
			/* TODO: check this for the 1.1 profile too */
			if (islistening)
				throw new InvalidOperationException ();
#endif
			serial = remoteEP.Serialize ();

			int error = 0;

			blocking_thread = Thread.CurrentThread;
			try {
				Connect_internal (socket, serial, out error);
			} catch (ThreadAbortException) {
				if (disposed) {
					Thread.ResetAbort ();
					error = (int) SocketError.Interrupted;
				}
			} finally {
				blocking_thread = null;
			}

			if (error != 0)
				throw new SocketException (error);

			connected=true;

#if NET_2_0
			isbound = true;
#endif

			seed_endpoint = remoteEP;
		}
예제 #13
0
 private void DoBeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint endPointSnapshot, SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
 {
     EndPoint endPoint = this.m_RightEndPoint;
       SocketError socketError = SocketError.SocketError;
       try
       {
     asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, true, ref this.Caches.ReceiveOverlappedCache);
     asyncResult.SocketAddressOriginal = endPointSnapshot.Serialize();
     if (this.m_RightEndPoint == null)
       this.m_RightEndPoint = endPointSnapshot;
     int bytesTransferred;
     socketError = UnsafeNclNativeMethods.OSSOCK.WSARecvFrom(this.m_Handle, ref asyncResult.m_SingleBuffer, 1, out bytesTransferred, out socketFlags, asyncResult.GetSocketAddressPtr(), asyncResult.GetSocketAddressSizePtr(), asyncResult.OverlappedHandle, IntPtr.Zero);
     if (socketError != SocketError.Success)
       socketError = (SocketError) Marshal.GetLastWin32Error();
       }
       catch (ObjectDisposedException ex)
       {
     this.m_RightEndPoint = endPoint;
     throw;
       }
       finally
       {
     socketError = asyncResult.CheckAsyncCallOverlappedResult(socketError);
       }
       if (socketError == SocketError.Success)
     return;
       this.m_RightEndPoint = endPoint;
       asyncResult.ExtractCache(ref this.Caches.ReceiveOverlappedCache);
       SocketException socketException = new SocketException(socketError);
       this.UpdateStatusAfterSocketError(socketException);
       if (Socket.s_LoggingEnabled)
     Logging.Exception(Logging.Sockets, (object) this, "BeginReceiveFrom", (Exception) socketException);
       throw socketException;
 }
예제 #14
0
 private SocketAddress CallSerializeCheckDnsEndPoint(EndPoint remoteEP)
 {
     if (!(remoteEP is DnsEndPoint))
     return remoteEP.Serialize();
       throw new ArgumentException(SR.GetString("net_sockets_invalid_dnsendpoint", new object[1]
       {
     (object) "remoteEP"
       }), "remoteEP");
 }
예제 #15
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;
     }
       }
 }
예제 #16
0
파일: Socket.cs 프로젝트: grendello/mono
		public void Bind (EndPoint localEP)
		{
#if FEATURE_NO_BSD_SOCKETS
			throw new PlatformNotSupportedException ("System.Net.Sockets.Socket:Bind is not supported on this platform.");
#else
			ThrowIfDisposedAndClosed ();

			if (localEP == null)
				throw new ArgumentNullException("localEP");
				
			var ipEndPoint = localEP as IPEndPoint;
			if (ipEndPoint != null) {
				localEP = RemapIPEndPoint (ipEndPoint);	
			}
			
			int error;
			Bind_internal (m_Handle, localEP.Serialize(), out error);

			if (error != 0)
				throw new SocketException (error);
			if (error == 0)
				is_bound = true;

			seed_endpoint = localEP;
#endif // FEATURE_NO_BSD_SOCKETS
		}
예제 #17
0
		internal int ReceiveFrom_nochecks_exc (byte [] buf, int offset, int size, SocketFlags flags,
						   ref EndPoint remote_end, bool throwOnError, out int error)
		{
			SocketAddress sockaddr = remote_end.Serialize();
			int cnt = RecvFrom_internal (socket, buf, offset, size, flags, ref sockaddr, out error);
			SocketError err = (SocketError) error;
			if (err != 0) {
				if (err != SocketError.WouldBlock && err != SocketError.InProgress)
					connected = false;
				else if (err == SocketError.WouldBlock && blocking) { // This might happen when ReceiveTimeout is set
					if (throwOnError)	
						throw new SocketException ((int) SocketError.TimedOut, "Operation timed out");
					error = (int) SocketError.TimedOut;
					return 0;
				}

				if (throwOnError)
					throw new SocketException (error);
				return 0;
			}

			connected = true;

#if NET_2_0
			isbound = true;
#endif

			// If sockaddr is null then we're a connection
			// oriented protocol and should ignore the
			// remote_end parameter (see MSDN
			// documentation for Socket.ReceiveFrom(...) )
			
			if ( sockaddr != null ) {
				// Stupidly, EndPoint.Create() is an
				// instance method
				remote_end = remote_end.Create (sockaddr);
			}
			
			seed_endpoint = remote_end;
			
			return cnt;
		}
예제 #18
0
		internal int SendTo_nochecks (byte [] buffer, int offset, int size, SocketFlags flags,
					      EndPoint remote_end)
		{
			SocketAddress sockaddr = remote_end.Serialize ();

			int ret, error;

			ret = SendTo_internal (socket, buffer, offset, size, flags, sockaddr, out error);

			SocketError err = (SocketError) error;
			if (err != 0) {
				if (err != SocketError.WouldBlock && err != SocketError.InProgress)
					connected = false;

				throw new SocketException (error);
			}

			connected = true;

#if NET_2_0
			isbound = true;
#endif
			
			seed_endpoint = remote_end;
			
			return ret;
		}
예제 #19
0
        public void Bind(EndPoint localEP)
        {
            if (m_Handle == -1)
            {
                throw new ObjectDisposedException();
            }

            NativeSocket.bind(this, localEP.Serialize().m_Buffer);

            m_localEndPoint = localEP;
        }
예제 #20
0
파일: Socket_2_1.cs 프로젝트: nlhepler/mono
		IAsyncResult BeginConnect(EndPoint end_point, AsyncCallback callback, object state)
		{
			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

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

			SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
			req.EndPoint = end_point;

			// Bug #75154: Connect() should not succeed for .Any addresses.
			if (end_point is IPEndPoint) {
				IPEndPoint ep = (IPEndPoint) end_point;
				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
					req.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
					return req;
				}
			}

			int error = 0;
			if (connect_in_progress) {
				// This could happen when multiple IPs are used
				// Calling connect() again will reset the connection attempt and cause
				// an error. Better to just close the socket and move on.
				connect_in_progress = false;
				Close_internal (socket, out error);
				socket = Socket_internal (address_family, socket_type, protocol_type, out error);
				if (error != 0)
					throw new SocketException (error);
			}
			bool blk = blocking;
			if (blk)
				Blocking = false;
			SocketAddress serial = end_point.Serialize ();
			Connect_internal (socket, serial, out error);
			if (blk)
				Blocking = true;
			if (error == 0) {
				// succeeded synch
				connected = true;
				isbound = true;
				req.Complete (true);
				return req;
			}

			if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
				// error synch
				connected = false;
				isbound = false;
				req.Complete (new SocketException (error), true);
				return req;
			}

			// continue asynch
			connected = false;
			isbound = false;
			connect_in_progress = true;
			socket_pool_queue (Worker.Dispatcher, req);
			return req;
		}
예제 #21
0
        public void Connect(EndPoint remoteEP)
        {
            if (m_Handle == -1)
            {
                throw new ObjectDisposedException();
            }

            NativeSocket.connect(this, remoteEP.Serialize().m_Buffer, !m_fBlocking);

            if (m_fBlocking)
            {
                Poll(-1, SelectMode.SelectWrite);
            }
        }
예제 #22
0
파일: Socket.cs 프로젝트: REALTOBIZ/mono
        private void DoBeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint endPointSnapshot, SocketAddress socketAddress, OverlappedAsyncResult asyncResult)
        {
            EndPoint oldEndPoint = m_RightEndPoint;
            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginReceiveFrom() size:" + size.ToString());

            // 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
            {
                // Set up asyncResult for overlapped WSARecvFrom.
                // This call will use completion ports on WinNT and Overlapped IO on Win9x.
                asyncResult.SetUnmanagedStructures(buffer, offset, size, socketAddress, true /* pin remoteEP*/, ref Caches.ReceiveOverlappedCache);

                // save a copy of the original EndPoint in the asyncResult
                asyncResult.SocketAddressOriginal = endPointSnapshot.Serialize();

                if (m_RightEndPoint == null) {
                    m_RightEndPoint = endPointSnapshot;
                }

                int bytesTransferred;
                errorCode = UnsafeNclNativeMethods.OSSOCK.WSARecvFrom(
                    m_Handle,
                    ref asyncResult.m_SingleBuffer,
                    1,
                    out bytesTransferred,
                    ref socketFlags,
                    asyncResult.GetSocketAddressPtr(),
                    asyncResult.GetSocketAddressSizePtr(),
                    asyncResult.OverlappedHandle,
                    IntPtr.Zero );

                if (errorCode!=SocketError.Success) {
                    errorCode = (SocketError)Marshal.GetLastWin32Error();
                }
                GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginReceiveFrom() UnsafeNclNativeMethods.OSSOCK.WSARecvFrom 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, "BeginReceiveFrom", socketException);
                throw socketException;
            }

            GlobalLog.Print("Socket#" + ValidationHelper.HashString(this) + "::DoBeginReceiveFrom() size:" + size.ToString() + " returning AsyncResult:" + ValidationHelper.HashString(asyncResult));
        }
예제 #23
0
        public int SendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP)
        {
            if (m_Handle == -1)
            {
                throw new ObjectDisposedException();
            }

            byte[] address = remoteEP.Serialize().m_Buffer;

            return NativeSocket.sendto(this, buffer, offset, size, (int)socketFlags, m_sendTimeout, address);
        }
예제 #24
0
		public void Connect (EndPoint remoteEP)
		{
			SocketAddress serial = null;

			if (disposed && closed)
				throw new ObjectDisposedException (GetType ().ToString ());

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

			IPEndPoint ep = remoteEP as IPEndPoint;
#if !MOONLIGHT
			if (ep != null && socket_type != SocketType.Dgram) /* Dgram uses Any to 'disconnect' */
#else
			if (ep != null)
#endif
				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
					throw new SocketException ((int) SocketError.AddressNotAvailable);

#if MOONLIGHT
			if (protocol_type != ProtocolType.Tcp)
				throw new SocketException ((int) SocketError.AccessDenied);
#else
			if (islistening)
				throw new InvalidOperationException ();
#endif
			serial = remoteEP.Serialize ();

			int error = 0;

			blocking_thread = Thread.CurrentThread;
			try {
				Connect_internal (socket, serial, out error);
			} catch (ThreadAbortException) {
				if (disposed) {
					Thread.ResetAbort ();
					error = (int) SocketError.Interrupted;
				}
			} finally {
				blocking_thread = null;
			}

			if (error == 0 || error == 10035)
				seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets

			if (error != 0)
				throw new SocketException (error);

#if !MOONLIGHT
			if (socket_type == SocketType.Dgram && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)))
				connected = false;
			else
				connected = true;
#else
			connected = true;
#endif
			isbound = true;
		}
예제 #25
0
        public int ReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP)
        {
            if (m_Handle == -1)
            {
                throw new ObjectDisposedException();
            }

            byte[] address = remoteEP.Serialize().m_Buffer;
            int len = 0;

            len = NativeSocket.recvfrom(this, buffer, offset, size, (int)socketFlags, m_recvTimeout, ref address);

            SocketAddress socketAddress = new SocketAddress(address);
            remoteEP = remoteEP.Create(socketAddress);

            return len;
        }
예제 #26
0
파일: Socket.cs 프로젝트: Profit0004/mono
		public void Bind (EndPoint local_end)
		{
			ThrowIfDisposedAndClosed ();

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

			int error;
			Bind_internal (safe_handle, local_end.Serialize(), out error);

			if (error != 0)
				throw new SocketException (error);
			if (error == 0)
				is_bound = true;

			seed_endpoint = local_end;
		}
예제 #27
0
파일: Socket.cs 프로젝트: Profit0004/mono
		internal int ReceiveFrom_nochecks_exc (byte [] buf, int offset, int size, SocketFlags flags, ref EndPoint remote_end, bool throwOnError, out int error)
		{
			SocketAddress sockaddr = remote_end.Serialize();

			int cnt = ReceiveFrom_internal (safe_handle, buf, offset, size, flags, ref sockaddr, out error);

			SocketError err = (SocketError) error;
			if (err != 0) {
				if (err != SocketError.WouldBlock && err != SocketError.InProgress) {
					is_connected = false;
				} else if (err == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set
					if (throwOnError)	
						throw new SocketException ((int) SocketError.TimedOut, TIMEOUT_EXCEPTION_MSG);
					error = (int) SocketError.TimedOut;
					return 0;
				}

				if (throwOnError)
					throw new SocketException (error);

				return 0;
			}

			is_connected = true;
			is_bound = true;

			/* If sockaddr is null then we're a connection oriented protocol and should ignore the
			 * remote_end parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */
			if (sockaddr != null) {
				/* Stupidly, EndPoint.Create() is an instance method */
				remote_end = remote_end.Create (sockaddr);
			}

			seed_endpoint = remote_end;

			return cnt;
		}
예제 #28
0
파일: Socket.cs 프로젝트: Profit0004/mono
		public IAsyncResult BeginConnect (EndPoint end_point, AsyncCallback callback, object state)
		{
			ThrowIfDisposedAndClosed ();

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

			SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
				EndPoint = end_point,
			};

			// Bug #75154: Connect() should not succeed for .Any addresses.
			if (end_point is IPEndPoint) {
				IPEndPoint ep = (IPEndPoint) end_point;
				if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
					sockares.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
					return sockares;
				}
			}

			int error = 0;

			if (connect_in_progress) {
				// This could happen when multiple IPs are used
				// Calling connect() again will reset the connection attempt and cause
				// an error. Better to just close the socket and move on.
				connect_in_progress = false;
				safe_handle.Dispose ();
				safe_handle = new SafeSocketHandle (Socket_internal (address_family, socket_type, protocol_type, out error), true);
				if (error != 0)
					throw new SocketException (error);
			}

			bool blk = is_blocking;
			if (blk)
				Blocking = false;
			Connect_internal (safe_handle, end_point.Serialize (), out error);
			if (blk)
				Blocking = true;

			if (error == 0) {
				// succeeded synch
				is_connected = true;
				is_bound = true;
				sockares.Complete (true);
				return sockares;
			}

			if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
				// error synch
				is_connected = false;
				is_bound = false;
				sockares.Complete (new SocketException (error), true);
				return sockares;
			}

			// continue asynch
			is_connected = false;
			is_bound = false;
			connect_in_progress = true;

			IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginConnectCallback, sockares));

			return sockares;
		}
예제 #29
0
파일: Socket.cs 프로젝트: grendello/mono
		internal int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, out SocketError errorCode)
		{
			SocketAddress sockaddr = remoteEP.Serialize();

			int nativeError;
			int cnt = ReceiveFrom_internal (m_Handle, buffer, offset, size, socketFlags, ref sockaddr, out nativeError, is_blocking);

			errorCode = (SocketError) nativeError;
			if (errorCode != SocketError.Success) {
				if (errorCode != SocketError.WouldBlock && errorCode != SocketError.InProgress) {
					is_connected = false;
				} else if (errorCode == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set
					errorCode = SocketError.TimedOut;
				}

				return 0;
			}

			is_connected = true;
			is_bound = true;

			/* If sockaddr is null then we're a connection oriented protocol and should ignore the
			 * remoteEP parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */
			if (sockaddr != null) {
				/* Stupidly, EndPoint.Create() is an instance method */
				remoteEP = remoteEP.Create (sockaddr);
			}

			seed_endpoint = remoteEP;

			return cnt;
		}
예제 #30
0
파일: Socket.cs 프로젝트: Profit0004/mono
		int SendTo_nochecks (byte [] buffer, int offset, int size, SocketFlags flags, EndPoint remote_end)
		{
			int error;
			int ret = SendTo_internal (safe_handle, buffer, offset, size, flags, remote_end.Serialize (), out error);

			SocketError err = (SocketError) error;
			if (err != 0) {
				if (err != SocketError.WouldBlock && err != SocketError.InProgress)
					is_connected = false;
				throw new SocketException (error);
			}

			is_connected = true;
			is_bound = true;
			seed_endpoint = remote_end;

			return ret;
		}
예제 #31
0
        public bool Connect(EndPoint remoteEP, int timeout)
        {
            // set the socket to non blocking
            socket.Blocking = false;

            // then we star the connect
            SocketAddress addr = remoteEP.Serialize();
            byte[] buff = new byte[addr.Size];
            for (int i=0; i<addr.Size; i++)
                buff[i] = addr[i];

            NativeMethods.connect(socket.Handle, buff, addr.Size);
            int wsaerror = NativeMethods.WSAGetLastError();
            if (wsaerror != 10035)
            {
                //  this is probably an IPV6 address
                if (wsaerror == 10047)
                    return false;
                throw new SocketException(wsaerror);
            }

            // next we wait for our connect timeout or until the socket is connected
            ArrayList write = new ArrayList();
            write.Add(socket);
            ArrayList error = new ArrayList();
            error.Add(socket);

            Socket.Select(null, write, error, timeout*1000*1000);

            if (write.Count == 0) return false;

            // set socket back to blocking mode
            socket.Blocking = true;
            return true;
        }