1 // System.Net.Sockets.Socket.cs
4 // Phillip Pearson (pp@myelin.co.nz)
5 // Dick Porter <dick@ximian.com>
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // Sridhar Kulkarni (sridharkulkarni@gmail.com)
8 // Brian Nickel (brian.nickel@gmail.com)
10 // Copyright (C) 2001, 2002 Phillip Pearson and Ximian, Inc.
11 // http://www.myelin.co.nz
12 // (c) 2004-2011 Novell, Inc. (http://www.novell.com)
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38 using System.Collections;
39 using System.Collections.Generic;
40 using System.Runtime.CompilerServices;
41 using System.Runtime.InteropServices;
42 using System.Threading;
44 using System.Security;
48 using System.Net.Configuration;
49 using System.Net.NetworkInformation;
51 #if MOONLIGHT && !INSIDE_SYSTEM
52 using System.Net.Policy;
55 namespace System.Net.Sockets {
57 public partial class Socket : IDisposable {
58 [StructLayout (LayoutKind.Sequential)]
64 // Used by the runtime
65 internal enum SocketOperation {
82 [StructLayout (LayoutKind.Sequential)]
83 internal sealed class SocketAsyncResult: IAsyncResult
85 /* Same structure in the runtime */
87 Keep this in sync with MonoSocketAsyncResult in
88 metadata/socket-io.h and ProcessAsyncReader
89 in System.Diagnostics/Process.cs.
95 AsyncCallback callback; // used from the runtime
96 WaitHandle waithandle;
98 Exception delayedException;
100 public EndPoint EndPoint; // Connect,ReceiveFrom,SendTo
101 public byte [] Buffer; // Receive,ReceiveFrom,Send,SendTo
102 public int Offset; // Receive,ReceiveFrom,Send,SendTo
103 public int Size; // Receive,ReceiveFrom,Send,SendTo
104 public SocketFlags SockFlags; // Receive,ReceiveFrom,Send,SendTo
105 public Socket AcceptSocket; // AcceptReceive
106 public IPAddress[] Addresses; // Connect
107 public int Port; // Connect
108 public IList<ArraySegment<byte>> Buffers; // Receive, Send
109 public bool ReuseSocket; // Disconnect
117 public bool blocking;
119 public SocketOperation operation;
121 public int EndCalled;
123 // These fields are not in MonoSocketAsyncResult
124 public Worker Worker;
125 public int CurrentAddress; // Connect
127 public SocketAsyncResult ()
131 public void Init (Socket sock, object state, AsyncCallback callback, SocketOperation operation)
135 this.blocking = sock.blocking;
136 this.handle = sock.socket;
138 this.blocking = true;
139 this.handle = IntPtr.Zero;
142 this.callback = callback;
143 GC.KeepAlive (this.callback);
144 this.operation = operation;
145 SockFlags = SocketFlags.None;
146 if (waithandle != null)
147 ((ManualResetEvent) waithandle).Reset ();
149 delayedException = null;
164 completed_sync = false;
173 public void DoMConnectCallback ()
175 if (callback == null)
178 ThreadPool.QueueUserWorkItem (_ => { callback (this); }, null);
180 ThreadPool.UnsafeQueueUserWorkItem (_ => { callback (this); }, null);
184 public void Dispose ()
186 Init (null, null, null, 0);
187 if (waithandle != null) {
193 public SocketAsyncResult (Socket sock, object state, AsyncCallback callback, SocketOperation operation)
196 this.blocking = sock.blocking;
197 this.handle = sock.socket;
199 this.callback = callback;
200 GC.KeepAlive (this.callback);
201 this.operation = operation;
202 SockFlags = SocketFlags.None;
203 Worker = new Worker (this);
206 public void CheckIfThrowDelayedException ()
208 if (delayedException != null) {
209 Sock.connected = false;
210 throw delayedException;
214 Sock.connected = false;
215 throw new SocketException (error);
219 void CompleteAllOnDispose (Queue queue)
221 object [] pending = queue.ToArray ();
225 for (int i = 0; i < pending.Length; i++) {
226 Worker worker = (Worker) pending [i];
227 SocketAsyncResult ares = worker.result;
228 cb = new WaitCallback (ares.CompleteDisposed);
230 ThreadPool.QueueUserWorkItem (cb, null);
232 ThreadPool.UnsafeQueueUserWorkItem (cb, null);
237 void CompleteDisposed (object unused)
242 public void Complete ()
244 if (operation != SocketOperation.Receive && Sock.disposed)
245 delayedException = new ObjectDisposedException (Sock.GetType ().ToString ());
250 if (operation == SocketOperation.Receive ||
251 operation == SocketOperation.ReceiveFrom ||
252 operation == SocketOperation.ReceiveGeneric) {
254 } else if (operation == SocketOperation.Send ||
255 operation == SocketOperation.SendTo ||
256 operation == SocketOperation.SendGeneric) {
262 Worker worker = null;
263 SocketAsyncCall sac = null;
265 // queue.Count will only be 0 if the socket is closed while receive/send
266 // operation(s) are pending and at least one call to this method is
267 // waiting on the lock while another one calls CompleteAllOnDispose()
269 queue.Dequeue (); // remove ourselves
270 if (queue.Count > 0) {
271 worker = (Worker) queue.Peek ();
272 if (!Sock.disposed) {
273 sac = Worker.Dispatcher;
275 CompleteAllOnDispose (queue);
281 Socket.socket_pool_queue (sac, worker.result);
283 // IMPORTANT: 'callback', if any is scheduled from unmanaged code
286 public void Complete (bool synch)
288 completed_sync = synch;
292 public void Complete (int total)
298 public void Complete (Exception e, bool synch)
300 completed_sync = synch;
301 delayedException = e;
305 public void Complete (Exception e)
307 delayedException = e;
311 public void Complete (Socket s)
317 public void Complete (Socket s, int total)
324 public object AsyncState {
330 public WaitHandle AsyncWaitHandle {
333 if (waithandle == null)
334 waithandle = new ManualResetEvent (completed);
344 public bool CompletedSynchronously {
346 return(completed_sync);
350 public bool IsCompleted {
357 if (waithandle != null && value) {
358 ((ManualResetEvent) waithandle).Set ();
364 public Socket Socket {
371 get { return total; }
372 set { total = value; }
375 public SocketError ErrorCode {
377 SocketException ex = delayedException as SocketException;
379 return(ex.SocketErrorCode);
382 return((SocketError)error);
384 return(SocketError.Success);
389 internal sealed class Worker
391 public SocketAsyncResult result;
392 SocketAsyncEventArgs args;
394 public Worker (SocketAsyncEventArgs args)
397 result = new SocketAsyncResult ();
398 result.Worker = this;
401 public Worker (SocketAsyncResult ares)
406 public void Dispose ()
408 if (result != null) {
415 public static SocketAsyncCall Dispatcher = new SocketAsyncCall (DispatcherCB);
417 static void DispatcherCB (SocketAsyncResult sar)
419 SocketOperation op = sar.operation;
420 if (op == Socket.SocketOperation.Receive || op == Socket.SocketOperation.ReceiveGeneric ||
421 op == Socket.SocketOperation.RecvJustCallback)
422 sar.Worker.Receive ();
423 else if (op == Socket.SocketOperation.Send || op == Socket.SocketOperation.SendGeneric ||
424 op == Socket.SocketOperation.SendJustCallback)
427 else if (op == Socket.SocketOperation.ReceiveFrom)
428 sar.Worker.ReceiveFrom ();
429 else if (op == Socket.SocketOperation.SendTo)
430 sar.Worker.SendTo ();
432 else if (op == Socket.SocketOperation.Connect)
433 sar.Worker.Connect ();
435 else if (op == Socket.SocketOperation.Accept)
436 sar.Worker.Accept ();
437 else if (op == Socket.SocketOperation.AcceptReceive)
438 sar.Worker.AcceptReceive ();
439 else if (op == Socket.SocketOperation.Disconnect)
440 sar.Worker.Disconnect ();
442 // SendPackets and ReceiveMessageFrom are not implemented yet
444 else if (op == Socket.SocketOperation.ReceiveMessageFrom)
445 async_op = SocketAsyncOperation.ReceiveMessageFrom;
446 else if (op == Socket.SocketOperation.SendPackets)
447 async_op = SocketAsyncOperation.SendPackets;
451 throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
454 /* This is called when reusing a SocketAsyncEventArgs */
455 public void Init (Socket sock, SocketAsyncEventArgs args, SocketOperation op)
457 result.Init (sock, args, SocketAsyncEventArgs.Dispatcher, op);
458 result.Worker = this;
459 SocketAsyncOperation async_op;
462 // -SocketOperation.AcceptReceive not used in SocketAsyncEventArgs
463 // -SendPackets and ReceiveMessageFrom are not implemented yet
464 if (op == Socket.SocketOperation.Connect)
465 async_op = SocketAsyncOperation.Connect;
467 else if (op == Socket.SocketOperation.Accept)
468 async_op = SocketAsyncOperation.Accept;
469 else if (op == Socket.SocketOperation.Disconnect)
470 async_op = SocketAsyncOperation.Disconnect;
472 else if (op == Socket.SocketOperation.Receive || op == Socket.SocketOperation.ReceiveGeneric)
473 async_op = SocketAsyncOperation.Receive;
475 else if (op == Socket.SocketOperation.ReceiveFrom)
476 async_op = SocketAsyncOperation.ReceiveFrom;
479 else if (op == Socket.SocketOperation.ReceiveMessageFrom)
480 async_op = SocketAsyncOperation.ReceiveMessageFrom;
482 else if (op == Socket.SocketOperation.Send || op == Socket.SocketOperation.SendGeneric)
483 async_op = SocketAsyncOperation.Send;
486 else if (op == Socket.SocketOperation.SendPackets)
487 async_op = SocketAsyncOperation.SendPackets;
489 else if (op == Socket.SocketOperation.SendTo)
490 async_op = SocketAsyncOperation.SendTo;
493 throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
495 args.SetLastOperation (async_op);
496 args.SocketError = SocketError.Success;
497 args.BytesTransferred = 0;
500 public void Accept ()
503 Socket acc_socket = null;
505 if (args != null && args.AcceptSocket != null) {
506 result.Sock.Accept (args.AcceptSocket);
507 acc_socket = args.AcceptSocket;
509 acc_socket = result.Sock.Accept ();
511 args.AcceptSocket = acc_socket;
513 } catch (Exception e) {
518 result.Complete (acc_socket);
522 /* only used in 2.0 profile and newer, but
523 * leave in older profiles to keep interface
524 * to runtime consistent
526 public void AcceptReceive ()
529 Socket acc_socket = null;
531 if (result.AcceptSocket == null) {
532 acc_socket = result.Sock.Accept ();
534 acc_socket = result.AcceptSocket;
535 result.Sock.Accept (acc_socket);
537 } catch (Exception e) {
542 /* It seems the MS runtime
543 * special-cases 0-length requested
544 * receive data. See bug 464201.
547 if (result.Size > 0) {
550 total = acc_socket.Receive_nochecks (result.Buffer,
556 result.Complete (new SocketException ((int) error));
559 } catch (Exception e) {
565 result.Complete (acc_socket, total);
569 public void Connect ()
571 if (result.EndPoint == null) {
572 result.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
576 SocketAsyncResult mconnect = result.AsyncState as SocketAsyncResult;
578 bool is_mconnect = (mconnect != null && mconnect.Addresses != null);
580 bool is_mconnect = false;
584 EndPoint ep = result.EndPoint;
585 error_code = (int) result.Sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
586 if (error_code == 0) {
589 result.Sock.seed_endpoint = ep;
590 result.Sock.connected = true;
591 result.Sock.isbound = true;
592 result.Sock.connect_in_progress = false;
596 result.DoMConnectCallback ();
601 result.Sock.connect_in_progress = false;
602 result.Complete (new SocketException (error_code));
606 if (mconnect.CurrentAddress >= mconnect.Addresses.Length) {
607 mconnect.Complete (new SocketException (error_code));
609 mconnect.DoMConnectCallback ();
612 mconnect.Sock.BeginMConnect (mconnect);
613 } catch (Exception e) {
614 result.Sock.connect_in_progress = false;
619 result.DoMConnectCallback ();
624 /* Also only used in 2.0 profile and newer */
625 public void Disconnect ()
630 result.ReuseSocket = args.DisconnectReuseSocket;
631 result.Sock.Disconnect (result.ReuseSocket);
632 } catch (Exception e) {
640 public void Receive ()
642 if (result.operation == SocketOperation.ReceiveGeneric) {
646 // Actual recv() done in the runtime
650 public void ReceiveFrom ()
655 total = result.Sock.ReceiveFrom_nochecks (result.Buffer,
659 ref result.EndPoint);
660 } catch (Exception e) {
665 result.Complete (total);
669 public void ReceiveGeneric ()
673 total = result.Sock.Receive (result.Buffers, result.SockFlags);
674 } catch (Exception e) {
678 result.Complete (total);
683 void UpdateSendValues (int last_sent)
685 if (result.error == 0) {
686 send_so_far += last_sent;
687 result.Offset += last_sent;
688 result.Size -= last_sent;
694 if (result.operation == SocketOperation.SendGeneric) {
698 // Actual send() done in the runtime
699 if (result.error == 0) {
700 UpdateSendValues (result.Total);
701 if (result.Sock.disposed) {
706 if (result.Size > 0) {
707 Socket.socket_pool_queue (Worker.Dispatcher, result);
708 return; // Have to finish writing everything. See bug #74475.
710 result.Total = send_so_far;
715 public void SendTo ()
720 total = result.Sock.SendTo_nochecks (result.Buffer,
726 UpdateSendValues (total);
727 if (result.Size > 0) {
728 Socket.socket_pool_queue (Worker.Dispatcher, result);
729 return; // Have to finish writing everything. See bug #74475.
731 result.Total = send_so_far;
732 } catch (Exception e) {
741 public void SendGeneric ()
745 total = result.Sock.Send (result.Buffers, result.SockFlags);
746 } catch (Exception e) {
750 result.Complete (total);
754 private Queue readQ = new Queue (2);
755 private Queue writeQ = new Queue (2);
757 internal delegate void SocketAsyncCall (SocketAsyncResult sar);
760 * These two fields are looked up by name by the runtime, don't change
761 * their name without also updating the runtime code.
763 private static int ipv4Supported = -1, ipv6Supported = -1;
768 // initialize ipv4Supported and ipv6Supported
769 CheckProtocolSupport ();
772 internal static void CheckProtocolSupport ()
774 if(ipv4Supported == -1) {
776 Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
785 if (ipv6Supported == -1) {
787 #if CONFIGURATION_DEP
788 SettingsSection config;
789 config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
791 ipv6Supported = config.Ipv6.Enabled ? -1 : 0;
793 NetConfig config = System.Configuration.ConfigurationSettings.GetConfig("system.net/settings") as NetConfig;
795 ipv6Supported = config.ipv6Enabled ? -1 : 0;
798 if (ipv6Supported != 0) {
800 Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
811 public static bool SupportsIPv4 {
813 CheckProtocolSupport();
814 return ipv4Supported == 1;
818 [ObsoleteAttribute ("Use OSSupportsIPv6 instead")]
819 public static bool SupportsIPv6 {
821 CheckProtocolSupport();
822 return ipv6Supported == 1;
826 public static bool OSSupportsIPv4 {
828 CheckProtocolSupport();
829 return ipv4Supported == 1;
834 public static bool OSSupportsIPv6 {
836 CheckProtocolSupport();
837 return ipv6Supported == 1;
841 public static bool OSSupportsIPv6 {
843 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
845 foreach (NetworkInterface adapter in nics) {
846 if (adapter.Supports (NetworkInterfaceComponent.IPv6))
854 /* the field "socket" is looked up by name by the runtime */
855 private IntPtr socket;
856 private AddressFamily address_family;
857 private SocketType socket_type;
858 private ProtocolType protocol_type;
859 internal bool blocking=true;
860 Thread blocking_thread;
861 private bool isbound;
862 /* When true, the socket was connected at the time of
863 * the last IO operation
865 private bool connected;
866 /* true if we called Close_internal */
868 internal bool disposed;
869 bool connect_in_progress;
872 * This EndPoint is used when creating new endpoints. Because
873 * there are many types of EndPoints possible,
874 * seed_endpoint.Create(addr) is used for creating new ones.
875 * As such, this value is set on Bind, SentTo, ReceiveFrom,
878 internal EndPoint seed_endpoint = null;
881 // Creates a new system socket, returning the handle
882 [MethodImplAttribute(MethodImplOptions.InternalCall)]
883 private extern IntPtr Socket_internal(AddressFamily family,
889 public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
891 #if NET_2_1 && !MOBILE
892 switch (addressFamily) {
893 case AddressFamily.InterNetwork: // ok
894 case AddressFamily.InterNetworkV6: // ok
895 case AddressFamily.Unknown: // SocketException will be thrown later (with right error #)
897 // case AddressFamily.Unspecified:
899 throw new ArgumentException ("addressFamily");
902 switch (socketType) {
903 case SocketType.Stream: // ok
904 case SocketType.Unknown: // SocketException will be thrown later (with right error #)
907 throw new ArgumentException ("socketType");
910 switch (protocolType) {
911 case ProtocolType.Tcp: // ok
912 case ProtocolType.Unspecified: // ok
913 case ProtocolType.Unknown: // SocketException will be thrown later (with right error #)
916 throw new ArgumentException ("protocolType");
919 address_family = addressFamily;
920 socket_type = socketType;
921 protocol_type = protocolType;
925 socket = Socket_internal (addressFamily, socketType, protocolType, out error);
927 throw new SocketException (error);
928 #if !NET_2_1 || MOBILE
939 public AddressFamily AddressFamily {
940 get { return address_family; }
944 [MethodImplAttribute(MethodImplOptions.InternalCall)]
945 private extern static void Blocking_internal(IntPtr socket,
950 public bool Blocking {
955 if (disposed && closed)
956 throw new ObjectDisposedException (GetType ().ToString ());
960 Blocking_internal (socket, value, out error);
963 throw new SocketException (error);
969 public bool Connected {
970 get { return connected; }
971 internal set { connected = value; }
974 public ProtocolType ProtocolType {
975 get { return protocol_type; }
978 public bool NoDelay {
980 if (disposed && closed)
981 throw new ObjectDisposedException (GetType ().ToString ());
985 return (int)(GetSocketOption (
986 SocketOptionLevel.Tcp,
987 SocketOptionName.NoDelay)) != 0;
991 if (disposed && closed)
992 throw new ObjectDisposedException (GetType ().ToString ());
997 SocketOptionLevel.Tcp,
998 SocketOptionName.NoDelay, value ? 1 : 0);
1002 public int ReceiveBufferSize {
1004 if (disposed && closed) {
1005 throw new ObjectDisposedException (GetType ().ToString ());
1007 return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer));
1010 if (disposed && closed) {
1011 throw new ObjectDisposedException (GetType ().ToString ());
1014 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1017 SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
1021 public int SendBufferSize {
1023 if (disposed && closed) {
1024 throw new ObjectDisposedException (GetType ().ToString ());
1026 return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer));
1029 if (disposed && closed) {
1030 throw new ObjectDisposedException (GetType ().ToString ());
1033 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1036 SetSocketOption (SocketOptionLevel.Socket,
1037 SocketOptionName.SendBuffer,
1044 if (disposed && closed) {
1045 throw new ObjectDisposedException (GetType ().ToString ());
1050 if (address_family == AddressFamily.InterNetwork) {
1051 ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive));
1052 } else if (address_family == AddressFamily.InterNetworkV6) {
1053 ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit));
1055 throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
1061 if (disposed && closed) {
1062 throw new ObjectDisposedException (GetType ().ToString ());
1065 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1068 if (address_family == AddressFamily.InterNetwork) {
1069 SetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, value);
1070 } else if (address_family == AddressFamily.InterNetworkV6) {
1071 SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit, value);
1073 throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
1078 // Returns the remote endpoint details in addr and port
1079 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1080 private extern static SocketAddress RemoteEndPoint_internal(IntPtr socket, int family, out int error);
1082 public EndPoint RemoteEndPoint {
1084 if (disposed && closed)
1085 throw new ObjectDisposedException (GetType ().ToString ());
1089 return seed_endpoint;
1092 * If the seed EndPoint is null, Connect, Bind,
1093 * etc has not yet been called. MS returns null
1096 if (!connected || seed_endpoint == null)
1102 sa=RemoteEndPoint_internal(socket, (int) address_family, out error);
1105 throw new SocketException (error);
1107 return seed_endpoint.Create (sa);
1111 void Linger (IntPtr handle)
1113 if (!connected || linger_timeout <= 0)
1116 // We don't want to receive any more data
1118 Shutdown_internal (handle, SocketShutdown.Receive, out error);
1122 int seconds = linger_timeout / 1000;
1123 int ms = linger_timeout % 1000;
1125 // If the other end closes, this will return 'true' with 'Available' == 0
1126 Poll_internal (handle, SelectMode.SelectRead, ms * 1000, out error);
1132 LingerOption linger = new LingerOption (true, seconds);
1133 SetSocketOption_internal (handle, SocketOptionLevel.Socket, SocketOptionName.Linger, linger, null, 0, out error);
1134 /* Not needed, we're closing upon return */
1140 protected virtual void Dispose (bool disposing)
1146 bool was_connected = connected;
1148 if ((int) socket != -1) {
1152 socket = (IntPtr) (-1);
1153 Thread th = blocking_thread;
1156 blocking_thread = null;
1161 //DateTime start = DateTime.UtcNow;
1162 Close_internal (x, out error);
1163 //Console.WriteLine ("Time spent in Close_internal: {0}ms", (DateTime.UtcNow - start).TotalMilliseconds);
1165 throw new SocketException (error);
1169 #if NET_2_1 || NET_4_0
1170 public void Dispose ()
1172 void IDisposable.Dispose ()
1176 GC.SuppressFinalize (this);
1179 // Closes the socket
1180 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1181 private extern static void Close_internal(IntPtr socket, out int error);
1183 public void Close ()
1186 ((IDisposable) this).Dispose ();
1189 public void Close (int timeout)
1191 linger_timeout = timeout;
1192 ((IDisposable) this).Dispose ();
1195 // Connects to the remote address
1196 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1197 private extern static void Connect_internal(IntPtr sock,
1201 public void Connect (EndPoint remoteEP)
1203 SocketAddress serial = null;
1205 if (disposed && closed)
1206 throw new ObjectDisposedException (GetType ().ToString ());
1208 if (remoteEP == null)
1209 throw new ArgumentNullException ("remoteEP");
1211 IPEndPoint ep = remoteEP as IPEndPoint;
1213 if (ep != null && socket_type != SocketType.Dgram) /* Dgram uses Any to 'disconnect' */
1217 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
1218 throw new SocketException ((int) SocketError.AddressNotAvailable);
1221 if (protocol_type != ProtocolType.Tcp)
1222 throw new SocketException ((int) SocketError.AccessDenied);
1225 throw new InvalidOperationException ();
1227 serial = remoteEP.Serialize ();
1231 blocking_thread = Thread.CurrentThread;
1233 Connect_internal (socket, serial, out error);
1234 } catch (ThreadAbortException) {
1236 Thread.ResetAbort ();
1237 error = (int) SocketError.Interrupted;
1240 blocking_thread = null;
1243 if (error == 0 || error == 10035)
1244 seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets
1247 throw new SocketException (error);
1250 if (socket_type == SocketType.Dgram && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)))
1260 public bool ReceiveAsync (SocketAsyncEventArgs e)
1262 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1263 if (disposed && closed)
1264 throw new ObjectDisposedException (GetType ().ToString ());
1266 // LAME SPEC: the ArgumentException is never thrown, instead an NRE is
1267 // thrown when e.Buffer and e.BufferList are null (works fine when one is
1268 // set to a valid object)
1269 if (e.Buffer == null && e.BufferList == null)
1270 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
1273 SocketOperation op = (e.Buffer != null) ? SocketOperation.Receive : SocketOperation.ReceiveGeneric;
1274 e.Worker.Init (this, e, op);
1275 SocketAsyncResult res = e.Worker.result;
1276 if (e.Buffer != null) {
1277 res.Buffer = e.Buffer;
1278 res.Offset = e.Offset;
1281 res.Buffers = e.BufferList;
1283 res.SockFlags = e.SocketFlags;
1286 readQ.Enqueue (e.Worker);
1287 count = readQ.Count;
1290 // Receive takes care of ReceiveGeneric
1291 socket_pool_queue (Worker.Dispatcher, res);
1297 public bool SendAsync (SocketAsyncEventArgs e)
1299 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1300 if (disposed && closed)
1301 throw new ObjectDisposedException (GetType ().ToString ());
1302 if (e.Buffer == null && e.BufferList == null)
1303 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
1306 SocketOperation op = (e.Buffer != null) ? SocketOperation.Send : SocketOperation.SendGeneric;
1307 e.Worker.Init (this, e, op);
1308 SocketAsyncResult res = e.Worker.result;
1309 if (e.Buffer != null) {
1310 res.Buffer = e.Buffer;
1311 res.Offset = e.Offset;
1314 res.Buffers = e.BufferList;
1316 res.SockFlags = e.SocketFlags;
1319 writeQ.Enqueue (e.Worker);
1320 count = writeQ.Count;
1323 // Send takes care of SendGeneric
1324 socket_pool_queue (Worker.Dispatcher, res);
1329 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1330 extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
1332 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1333 private extern static int Receive_internal(IntPtr sock,
1340 internal int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
1343 int ret = Receive_internal (socket, buf, offset, size, flags, out nativeError);
1344 error = (SocketError) nativeError;
1345 if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
1355 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1356 private extern static void GetSocketOption_obj_internal(IntPtr socket,
1357 SocketOptionLevel level, SocketOptionName name, out object obj_val,
1360 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1361 private extern static int Send_internal(IntPtr sock,
1362 byte[] buf, int offset,
1367 internal int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
1370 error = SocketError.Success;
1376 int ret = Send_internal (socket, buf, offset, size, flags, out nativeError);
1378 error = (SocketError)nativeError;
1380 if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
1390 public object GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName)
1392 if (disposed && closed)
1393 throw new ObjectDisposedException (GetType ().ToString ());
1398 GetSocketOption_obj_internal (socket, optionLevel, optionName, out obj_val,
1401 throw new SocketException (error);
1403 if (optionName == SocketOptionName.Linger) {
1404 return((LingerOption)obj_val);
1405 } else if (optionName == SocketOptionName.AddMembership ||
1406 optionName == SocketOptionName.DropMembership) {
1407 return((MulticastOption)obj_val);
1408 } else if (obj_val is int) {
1409 return((int)obj_val);
1415 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1416 private extern static void Shutdown_internal (IntPtr socket, SocketShutdown how, out int error);
1418 public void Shutdown (SocketShutdown how)
1420 if (disposed && closed)
1421 throw new ObjectDisposedException (GetType ().ToString ());
1424 throw new SocketException (10057); // Not connected
1428 Shutdown_internal (socket, how, out error);
1430 throw new SocketException (error);
1433 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1434 private extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level,
1435 SocketOptionName name, object obj_val,
1436 byte [] byte_val, int int_val,
1439 public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
1441 if (disposed && closed)
1442 throw new ObjectDisposedException (GetType ().ToString ());
1446 SetSocketOption_internal (socket, optionLevel, optionName, null,
1447 null, optionValue, out error);
1450 throw new SocketException (error);
1453 private void ThrowIfUpd ()
1455 #if !NET_2_1 || MOBILE
1456 if (protocol_type == ProtocolType.Udp)
1457 throw new SocketException ((int)SocketError.ProtocolOption);
1464 IAsyncResult BeginConnect(EndPoint end_point, AsyncCallback callback, object state)
1466 if (disposed && closed)
1467 throw new ObjectDisposedException (GetType ().ToString ());
1469 if (end_point == null)
1470 throw new ArgumentNullException ("end_point");
1472 SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
1473 req.EndPoint = end_point;
1475 // Bug #75154: Connect() should not succeed for .Any addresses.
1476 if (end_point is IPEndPoint) {
1477 IPEndPoint ep = (IPEndPoint) end_point;
1478 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
1479 req.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
1485 if (connect_in_progress) {
1486 // This could happen when multiple IPs are used
1487 // Calling connect() again will reset the connection attempt and cause
1488 // an error. Better to just close the socket and move on.
1489 connect_in_progress = false;
1490 Close_internal (socket, out error);
1491 socket = Socket_internal (address_family, socket_type, protocol_type, out error);
1493 throw new SocketException (error);
1495 bool blk = blocking;
1498 SocketAddress serial = end_point.Serialize ();
1499 Connect_internal (socket, serial, out error);
1506 req.Complete (true);
1510 if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
1514 req.Complete (new SocketException (error), true);
1521 connect_in_progress = true;
1522 socket_pool_queue (Worker.Dispatcher, req);
1531 IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback callback, object state)
1534 if (disposed && closed)
1535 throw new ObjectDisposedException (GetType ().ToString ());
1537 if (addresses == null)
1538 throw new ArgumentNullException ("addresses");
1540 if (addresses.Length == 0)
1541 throw new ArgumentException ("Empty addresses list");
1543 if (this.AddressFamily != AddressFamily.InterNetwork &&
1544 this.AddressFamily != AddressFamily.InterNetworkV6)
1545 throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
1547 if (port <= 0 || port > 65535)
1548 throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
1551 throw new InvalidOperationException ();
1554 SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
1555 req.Addresses = addresses;
1558 return BeginMConnect (req);
1561 IAsyncResult BeginMConnect (SocketAsyncResult req)
1563 IAsyncResult ares = null;
1564 Exception exc = null;
1565 for (int i = req.CurrentAddress; i < req.Addresses.Length; i++) {
1566 IPAddress addr = req.Addresses [i];
1567 IPEndPoint ep = new IPEndPoint (addr, req.Port);
1569 req.CurrentAddress++;
1570 ares = BeginConnect (ep, null, req);
1571 if (ares.IsCompleted && ares.CompletedSynchronously) {
1572 ((SocketAsyncResult) ares).CheckIfThrowDelayedException ();
1573 req.DoMConnectCallback ();
1576 } catch (Exception e) {
1588 // Returns false when it is ok to use RemoteEndPoint
1589 // true when addresses must be used (and addresses could be null/empty)
1590 bool GetCheckedIPs (SocketAsyncEventArgs e, out IPAddress [] addresses)
1593 #if MOONLIGHT || NET_4_0
1594 // Connect to the first address that match the host name, like:
1595 // http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
1596 // while skipping entries that do not match the address family
1597 DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
1599 addresses = Dns.GetHostAddresses (dep.Host);
1600 IPEndPoint endpoint;
1601 #if MOONLIGHT && !INSIDE_SYSTEM
1602 if (!e.PolicyRestricted && !SecurityManager.HasElevatedPermissions) {
1603 List<IPAddress> valid = new List<IPAddress> ();
1604 foreach (IPAddress a in addresses) {
1605 // if we're not downloading a socket policy then check the policy
1606 // and if we're not running with elevated permissions (SL4 OoB option)
1607 endpoint = new IPEndPoint (a, dep.Port);
1608 if (!CrossDomainPolicyManager.CheckEndPoint (endpoint, e.SocketClientAccessPolicyProtocol))
1612 addresses = valid.ToArray ();
1617 e.ConnectByNameError = null;
1618 #if MOONLIGHT && !INSIDE_SYSTEM
1619 if (!e.PolicyRestricted && !SecurityManager.HasElevatedPermissions) {
1620 if (CrossDomainPolicyManager.CheckEndPoint (e.RemoteEndPoint, e.SocketClientAccessPolicyProtocol))
1626 return true; // do not use remote endpoint
1628 return false; // < NET_4_0 -> use remote endpoint
1632 bool ConnectAsyncReal (SocketAsyncEventArgs e)
1634 IPAddress [] addresses = null;
1635 bool use_remoteep = true;
1636 #if MOONLIGHT || NET_4_0
1637 use_remoteep = !GetCheckedIPs (e, out addresses);
1640 Worker w = e.Worker;
1641 w.Init (this, e, SocketOperation.Connect);
1642 SocketAsyncResult result = w.result;
1643 IAsyncResult ares = null;
1646 result.EndPoint = e.RemoteEndPoint;
1647 ares = BeginConnect (e.RemoteEndPoint, SocketAsyncEventArgs.Dispatcher, e);
1649 #if MOONLIGHT || NET_4_0
1652 DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
1653 result.Addresses = addresses;
1654 result.Port = dep.Port;
1656 ares = BeginConnect (addresses, dep.Port, SocketAsyncEventArgs.Dispatcher, e);
1659 if (ares.IsCompleted && ares.CompletedSynchronously) {
1660 ((SocketAsyncResult) ares).CheckIfThrowDelayedException ();
1663 } catch (Exception exc) {
1664 result.Complete (exc, true);
1671 public bool ConnectAsync (SocketAsyncEventArgs e)
1673 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1674 if (disposed && closed)
1675 throw new ObjectDisposedException (GetType ().ToString ());
1677 throw new InvalidOperationException ("You may not perform this operation after calling the Listen method.");
1678 if (e.RemoteEndPoint == null)
1679 throw new ArgumentNullException ("remoteEP");
1681 return ConnectAsyncReal (e);
1685 static void CheckConnect (SocketAsyncEventArgs e)
1687 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1689 if (e.RemoteEndPoint == null)
1690 throw new ArgumentNullException ("remoteEP");
1691 if (e.BufferList != null)
1692 throw new ArgumentException ("Multiple buffers cannot be used with this method.");
1695 public bool ConnectAsync (SocketAsyncEventArgs e)
1697 if (disposed && closed)
1698 throw new ObjectDisposedException (GetType ().ToString ());
1701 // if an address family is specified then they must match
1702 AddressFamily raf = e.RemoteEndPoint.AddressFamily;
1703 if ((raf != AddressFamily.Unspecified) && (raf != AddressFamily))
1704 throw new NotSupportedException ("AddressFamily mismatch between socket and endpoint");
1706 return ConnectAsyncReal (e);
1709 public static bool ConnectAsync (SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
1711 // exception ordering requires to check before creating the socket (good thing resource wise too)
1714 // create socket based on the endpoint address family (if specified), otherwise default fo IPv4
1715 AddressFamily raf = e.RemoteEndPoint.AddressFamily;
1716 if (raf == AddressFamily.Unspecified)
1717 raf = AddressFamily.InterNetwork;
1718 Socket s = new Socket (raf, socketType, protocolType);
1719 return s.ConnectAsyncReal (e);
1722 public static void CancelConnectAsync (SocketAsyncEventArgs e)
1725 throw new ArgumentNullException ("e");
1727 // FIXME: this is canceling a synchronous connect, not an async one
1728 Socket s = e.ConnectSocket;
1729 if ((s != null) && (s.blocking_thread != null))
1730 s.blocking_thread.Abort ();
1733 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1734 private extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
1740 int Receive (IList<ArraySegment<byte>> buffers)
1744 ret = Receive (buffers, SocketFlags.None, out error);
1745 if (error != SocketError.Success) {
1746 throw new SocketException ((int)error);
1751 [CLSCompliant (false)]
1757 int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1761 ret = Receive (buffers, socketFlags, out error);
1762 if (error != SocketError.Success) {
1763 throw new SocketException ((int)error);
1768 [CLSCompliant (false)]
1774 int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1776 if (disposed && closed)
1777 throw new ObjectDisposedException (GetType ().ToString ());
1779 if (buffers == null ||
1780 buffers.Count == 0) {
1781 throw new ArgumentNullException ("buffers");
1784 int numsegments = buffers.Count;
1788 /* Only example I can find of sending a byte
1789 * array reference directly into an internal
1791 * System.Runtime.Remoting/System.Runtime.Remoting.Channels.Ipc.Win32/NamedPipeSocket.cs,
1792 * so taking a lead from that...
1794 WSABUF[] bufarray = new WSABUF[numsegments];
1795 GCHandle[] gch = new GCHandle[numsegments];
1797 for(int i = 0; i < numsegments; i++) {
1798 ArraySegment<byte> segment = buffers[i];
1799 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
1800 bufarray[i].len = segment.Count;
1801 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
1805 ret = Receive_internal (socket, bufarray,
1809 for(int i = 0; i < numsegments; i++) {
1810 if (gch[i].IsAllocated) {
1816 errorCode = (SocketError)nativeError;
1820 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1821 private extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
1827 int Send (IList<ArraySegment<byte>> buffers)
1831 ret = Send (buffers, SocketFlags.None, out error);
1832 if (error != SocketError.Success) {
1833 throw new SocketException ((int)error);
1843 int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1847 ret = Send (buffers, socketFlags, out error);
1848 if (error != SocketError.Success) {
1849 throw new SocketException ((int)error);
1854 [CLSCompliant (false)]
1860 int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1862 if (disposed && closed)
1863 throw new ObjectDisposedException (GetType ().ToString ());
1864 if (buffers == null)
1865 throw new ArgumentNullException ("buffers");
1866 if (buffers.Count == 0)
1867 throw new ArgumentException ("Buffer is empty", "buffers");
1868 int numsegments = buffers.Count;
1872 WSABUF[] bufarray = new WSABUF[numsegments];
1873 GCHandle[] gch = new GCHandle[numsegments];
1874 for(int i = 0; i < numsegments; i++) {
1875 ArraySegment<byte> segment = buffers[i];
1876 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
1877 bufarray[i].len = segment.Count;
1878 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
1882 ret = Send_internal (socket, bufarray, socketFlags, out nativeError);
1884 for(int i = 0; i < numsegments; i++) {
1885 if (gch[i].IsAllocated) {
1890 errorCode = (SocketError)nativeError;
1894 Exception InvalidAsyncOp (string method)
1896 return new InvalidOperationException (method + " can only be called once per asynchronous operation");
1904 int EndReceive (IAsyncResult result)
1907 int bytesReceived = EndReceive (result, out error);
1908 if (error != SocketError.Success) {
1909 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
1911 throw new SocketException ((int)error);
1913 return bytesReceived;
1921 int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
1923 if (disposed && closed)
1924 throw new ObjectDisposedException (GetType ().ToString ());
1926 if (asyncResult == null)
1927 throw new ArgumentNullException ("asyncResult");
1929 SocketAsyncResult req = asyncResult as SocketAsyncResult;
1931 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
1933 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
1934 throw InvalidAsyncOp ("EndReceive");
1935 if (!asyncResult.IsCompleted)
1936 asyncResult.AsyncWaitHandle.WaitOne ();
1938 errorCode = req.ErrorCode;
1939 // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
1940 // kinds of exceptions that should be thrown.
1941 if (errorCode == SocketError.Success)
1942 req.CheckIfThrowDelayedException();
1952 int EndSend (IAsyncResult result)
1955 int bytesSent = EndSend (result, out error);
1956 if (error != SocketError.Success) {
1957 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
1959 throw new SocketException ((int)error);
1969 int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
1971 if (disposed && closed)
1972 throw new ObjectDisposedException (GetType ().ToString ());
1973 if (asyncResult == null)
1974 throw new ArgumentNullException ("asyncResult");
1976 SocketAsyncResult req = asyncResult as SocketAsyncResult;
1978 throw new ArgumentException ("Invalid IAsyncResult", "result");
1980 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
1981 throw InvalidAsyncOp ("EndSend");
1982 if (!asyncResult.IsCompleted)
1983 asyncResult.AsyncWaitHandle.WaitOne ();
1985 errorCode = req.ErrorCode;
1986 // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
1987 // kinds of exceptions that should be thrown.
1988 if (errorCode == SocketError.Success)
1989 req.CheckIfThrowDelayedException ();
1994 // Used by Udpclient
2000 int EndReceiveFrom(IAsyncResult result, ref EndPoint end_point)
2002 if (disposed && closed)
2003 throw new ObjectDisposedException (GetType ().ToString ());
2006 throw new ArgumentNullException ("result");
2008 if (end_point == null)
2009 throw new ArgumentNullException ("remote_end");
2011 SocketAsyncResult req = result as SocketAsyncResult;
2013 throw new ArgumentException ("Invalid IAsyncResult", "result");
2015 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
2016 throw InvalidAsyncOp ("EndReceiveFrom");
2017 if (!result.IsCompleted)
2018 result.AsyncWaitHandle.WaitOne();
2020 req.CheckIfThrowDelayedException();
2021 end_point = req.EndPoint;
2025 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2026 static extern void socket_pool_queue (SocketAsyncCall d, SocketAsyncResult r);