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;
501 public void Accept ()
504 Socket acc_socket = null;
506 if (args != null && args.AcceptSocket != null) {
507 result.Sock.Accept (args.AcceptSocket);
508 acc_socket = args.AcceptSocket;
510 acc_socket = result.Sock.Accept ();
512 args.AcceptSocket = acc_socket;
514 } catch (Exception e) {
519 result.Complete (acc_socket);
523 /* only used in 2.0 profile and newer, but
524 * leave in older profiles to keep interface
525 * to runtime consistent
527 public void AcceptReceive ()
530 Socket acc_socket = null;
532 if (result.AcceptSocket == null) {
533 acc_socket = result.Sock.Accept ();
535 acc_socket = result.AcceptSocket;
536 result.Sock.Accept (acc_socket);
538 } catch (Exception e) {
543 /* It seems the MS runtime
544 * special-cases 0-length requested
545 * receive data. See bug 464201.
548 if (result.Size > 0) {
551 total = acc_socket.Receive_nochecks (result.Buffer,
557 result.Complete (new SocketException ((int) error));
560 } catch (Exception e) {
566 result.Complete (acc_socket, total);
570 public void Connect ()
572 if (result.EndPoint == null) {
573 result.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
577 SocketAsyncResult mconnect = result.AsyncState as SocketAsyncResult;
579 bool is_mconnect = (mconnect != null && mconnect.Addresses != null);
581 if (result.ErrorCode == SocketError.AccessDenied) {
583 result.DoMConnectCallback ();
586 bool is_mconnect = false;
590 EndPoint ep = result.EndPoint;
591 error_code = (int) result.Sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
592 if (error_code == 0) {
595 result.Sock.seed_endpoint = ep;
596 result.Sock.connected = true;
597 result.Sock.isbound = true;
598 result.Sock.connect_in_progress = false;
602 result.DoMConnectCallback ();
607 result.Sock.connect_in_progress = false;
608 result.Complete (new SocketException (error_code));
612 if (mconnect.CurrentAddress >= mconnect.Addresses.Length) {
613 mconnect.Complete (new SocketException (error_code));
615 mconnect.DoMConnectCallback ();
618 mconnect.Sock.BeginMConnect (mconnect);
619 } catch (Exception e) {
620 result.Sock.connect_in_progress = false;
625 result.DoMConnectCallback ();
630 /* Also only used in 2.0 profile and newer */
631 public void Disconnect ()
636 result.ReuseSocket = args.DisconnectReuseSocket;
637 result.Sock.Disconnect (result.ReuseSocket);
638 } catch (Exception e) {
646 public void Receive ()
648 if (result.operation == SocketOperation.ReceiveGeneric) {
652 // Actual recv() done in the runtime
656 public void ReceiveFrom ()
661 total = result.Sock.ReceiveFrom_nochecks (result.Buffer,
665 ref result.EndPoint);
666 } catch (Exception e) {
671 result.Complete (total);
675 public void ReceiveGeneric ()
679 total = result.Sock.Receive (result.Buffers, result.SockFlags);
680 } catch (Exception e) {
684 result.Complete (total);
689 void UpdateSendValues (int last_sent)
691 if (result.error == 0) {
692 send_so_far += last_sent;
693 result.Offset += last_sent;
694 result.Size -= last_sent;
700 if (result.operation == SocketOperation.SendGeneric) {
704 // Actual send() done in the runtime
705 if (result.error == 0) {
706 UpdateSendValues (result.Total);
707 if (result.Sock.disposed) {
712 if (result.Size > 0) {
713 Socket.socket_pool_queue (Worker.Dispatcher, result);
714 return; // Have to finish writing everything. See bug #74475.
716 result.Total = send_so_far;
721 public void SendTo ()
726 total = result.Sock.SendTo_nochecks (result.Buffer,
732 UpdateSendValues (total);
733 if (result.Size > 0) {
734 Socket.socket_pool_queue (Worker.Dispatcher, result);
735 return; // Have to finish writing everything. See bug #74475.
737 result.Total = send_so_far;
738 } catch (Exception e) {
747 public void SendGeneric ()
751 total = result.Sock.Send (result.Buffers, result.SockFlags);
752 } catch (Exception e) {
756 result.Complete (total);
760 private Queue readQ = new Queue (2);
761 private Queue writeQ = new Queue (2);
763 internal delegate void SocketAsyncCall (SocketAsyncResult sar);
766 * These two fields are looked up by name by the runtime, don't change
767 * their name without also updating the runtime code.
769 private static int ipv4Supported = -1, ipv6Supported = -1;
774 // initialize ipv4Supported and ipv6Supported
775 CheckProtocolSupport ();
778 internal static void CheckProtocolSupport ()
780 if(ipv4Supported == -1) {
782 Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
791 if (ipv6Supported == -1) {
793 #if CONFIGURATION_DEP
794 SettingsSection config;
795 config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
797 ipv6Supported = config.Ipv6.Enabled ? -1 : 0;
799 NetConfig config = System.Configuration.ConfigurationSettings.GetConfig("system.net/settings") as NetConfig;
801 ipv6Supported = config.ipv6Enabled ? -1 : 0;
804 if (ipv6Supported != 0) {
806 Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
817 public static bool SupportsIPv4 {
819 CheckProtocolSupport();
820 return ipv4Supported == 1;
824 [ObsoleteAttribute ("Use OSSupportsIPv6 instead")]
825 public static bool SupportsIPv6 {
827 CheckProtocolSupport();
828 return ipv6Supported == 1;
832 public static bool OSSupportsIPv4 {
834 CheckProtocolSupport();
835 return ipv4Supported == 1;
840 public static bool OSSupportsIPv6 {
842 CheckProtocolSupport();
843 return ipv6Supported == 1;
847 public static bool OSSupportsIPv6 {
849 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
851 foreach (NetworkInterface adapter in nics) {
852 if (adapter.Supports (NetworkInterfaceComponent.IPv6))
860 /* the field "socket" is looked up by name by the runtime */
861 private IntPtr socket;
862 private AddressFamily address_family;
863 private SocketType socket_type;
864 private ProtocolType protocol_type;
865 internal bool blocking=true;
866 Thread blocking_thread;
867 private bool isbound;
868 /* When true, the socket was connected at the time of
869 * the last IO operation
871 private bool connected;
872 /* true if we called Close_internal */
874 internal bool disposed;
875 bool connect_in_progress;
878 * This EndPoint is used when creating new endpoints. Because
879 * there are many types of EndPoints possible,
880 * seed_endpoint.Create(addr) is used for creating new ones.
881 * As such, this value is set on Bind, SentTo, ReceiveFrom,
884 internal EndPoint seed_endpoint = null;
887 // Creates a new system socket, returning the handle
888 [MethodImplAttribute(MethodImplOptions.InternalCall)]
889 private extern IntPtr Socket_internal(AddressFamily family,
895 public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
897 #if NET_2_1 && !MOBILE
898 switch (addressFamily) {
899 case AddressFamily.InterNetwork: // ok
900 case AddressFamily.InterNetworkV6: // ok
901 case AddressFamily.Unknown: // SocketException will be thrown later (with right error #)
903 // case AddressFamily.Unspecified:
905 throw new ArgumentException ("addressFamily");
908 switch (socketType) {
909 case SocketType.Stream: // ok
910 case SocketType.Unknown: // SocketException will be thrown later (with right error #)
913 throw new ArgumentException ("socketType");
916 switch (protocolType) {
917 case ProtocolType.Tcp: // ok
918 case ProtocolType.Unspecified: // ok
919 case ProtocolType.Unknown: // SocketException will be thrown later (with right error #)
922 throw new ArgumentException ("protocolType");
925 address_family = addressFamily;
926 socket_type = socketType;
927 protocol_type = protocolType;
931 socket = Socket_internal (addressFamily, socketType, protocolType, out error);
933 throw new SocketException (error);
934 #if !NET_2_1 || MOBILE
945 public AddressFamily AddressFamily {
946 get { return address_family; }
950 [MethodImplAttribute(MethodImplOptions.InternalCall)]
951 private extern static void Blocking_internal(IntPtr socket,
956 public bool Blocking {
961 if (disposed && closed)
962 throw new ObjectDisposedException (GetType ().ToString ());
966 Blocking_internal (socket, value, out error);
969 throw new SocketException (error);
975 public bool Connected {
976 get { return connected; }
977 internal set { connected = value; }
980 public ProtocolType ProtocolType {
981 get { return protocol_type; }
984 public bool NoDelay {
986 if (disposed && closed)
987 throw new ObjectDisposedException (GetType ().ToString ());
991 return (int)(GetSocketOption (
992 SocketOptionLevel.Tcp,
993 SocketOptionName.NoDelay)) != 0;
997 if (disposed && closed)
998 throw new ObjectDisposedException (GetType ().ToString ());
1003 SocketOptionLevel.Tcp,
1004 SocketOptionName.NoDelay, value ? 1 : 0);
1008 public int ReceiveBufferSize {
1010 if (disposed && closed) {
1011 throw new ObjectDisposedException (GetType ().ToString ());
1013 return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer));
1016 if (disposed && closed) {
1017 throw new ObjectDisposedException (GetType ().ToString ());
1020 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1023 SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
1027 public int SendBufferSize {
1029 if (disposed && closed) {
1030 throw new ObjectDisposedException (GetType ().ToString ());
1032 return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer));
1035 if (disposed && closed) {
1036 throw new ObjectDisposedException (GetType ().ToString ());
1039 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1042 SetSocketOption (SocketOptionLevel.Socket,
1043 SocketOptionName.SendBuffer,
1050 if (disposed && closed) {
1051 throw new ObjectDisposedException (GetType ().ToString ());
1056 if (address_family == AddressFamily.InterNetwork) {
1057 ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive));
1058 } else if (address_family == AddressFamily.InterNetworkV6) {
1059 ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit));
1061 throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
1067 if (disposed && closed) {
1068 throw new ObjectDisposedException (GetType ().ToString ());
1071 throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
1074 if (address_family == AddressFamily.InterNetwork) {
1075 SetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, value);
1076 } else if (address_family == AddressFamily.InterNetworkV6) {
1077 SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit, value);
1079 throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
1084 // Returns the remote endpoint details in addr and port
1085 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1086 private extern static SocketAddress RemoteEndPoint_internal(IntPtr socket, int family, out int error);
1088 public EndPoint RemoteEndPoint {
1090 if (disposed && closed)
1091 throw new ObjectDisposedException (GetType ().ToString ());
1095 return seed_endpoint;
1098 * If the seed EndPoint is null, Connect, Bind,
1099 * etc has not yet been called. MS returns null
1102 if (!connected || seed_endpoint == null)
1108 sa=RemoteEndPoint_internal(socket, (int) address_family, out error);
1111 throw new SocketException (error);
1113 return seed_endpoint.Create (sa);
1117 void Linger (IntPtr handle)
1119 if (!connected || linger_timeout <= 0)
1122 // We don't want to receive any more data
1124 Shutdown_internal (handle, SocketShutdown.Receive, out error);
1128 int seconds = linger_timeout / 1000;
1129 int ms = linger_timeout % 1000;
1131 // If the other end closes, this will return 'true' with 'Available' == 0
1132 Poll_internal (handle, SelectMode.SelectRead, ms * 1000, out error);
1138 LingerOption linger = new LingerOption (true, seconds);
1139 SetSocketOption_internal (handle, SocketOptionLevel.Socket, SocketOptionName.Linger, linger, null, 0, out error);
1140 /* Not needed, we're closing upon return */
1146 protected virtual void Dispose (bool disposing)
1152 bool was_connected = connected;
1154 if ((int) socket != -1) {
1158 socket = (IntPtr) (-1);
1159 Thread th = blocking_thread;
1162 blocking_thread = null;
1167 //DateTime start = DateTime.UtcNow;
1168 Close_internal (x, out error);
1169 //Console.WriteLine ("Time spent in Close_internal: {0}ms", (DateTime.UtcNow - start).TotalMilliseconds);
1171 throw new SocketException (error);
1175 #if NET_2_1 || NET_4_0
1176 public void Dispose ()
1178 void IDisposable.Dispose ()
1182 GC.SuppressFinalize (this);
1185 // Closes the socket
1186 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1187 private extern static void Close_internal(IntPtr socket, out int error);
1189 public void Close ()
1192 ((IDisposable) this).Dispose ();
1195 public void Close (int timeout)
1197 linger_timeout = timeout;
1198 ((IDisposable) this).Dispose ();
1201 // Connects to the remote address
1202 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1203 private extern static void Connect_internal(IntPtr sock,
1207 public void Connect (EndPoint remoteEP)
1209 SocketAddress serial = null;
1211 if (disposed && closed)
1212 throw new ObjectDisposedException (GetType ().ToString ());
1214 if (remoteEP == null)
1215 throw new ArgumentNullException ("remoteEP");
1217 IPEndPoint ep = remoteEP as IPEndPoint;
1219 if (ep != null && socket_type != SocketType.Dgram) /* Dgram uses Any to 'disconnect' */
1223 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
1224 throw new SocketException ((int) SocketError.AddressNotAvailable);
1227 if (protocol_type != ProtocolType.Tcp)
1228 throw new SocketException ((int) SocketError.AccessDenied);
1231 throw new InvalidOperationException ();
1233 serial = remoteEP.Serialize ();
1237 blocking_thread = Thread.CurrentThread;
1239 Connect_internal (socket, serial, out error);
1240 } catch (ThreadAbortException) {
1242 Thread.ResetAbort ();
1243 error = (int) SocketError.Interrupted;
1246 blocking_thread = null;
1249 if (error == 0 || error == 10035)
1250 seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets
1253 throw new SocketException (error);
1256 if (socket_type == SocketType.Dgram && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)))
1266 public bool ReceiveAsync (SocketAsyncEventArgs e)
1268 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1269 if (disposed && closed)
1270 throw new ObjectDisposedException (GetType ().ToString ());
1272 // LAME SPEC: the ArgumentException is never thrown, instead an NRE is
1273 // thrown when e.Buffer and e.BufferList are null (works fine when one is
1274 // set to a valid object)
1275 if (e.Buffer == null && e.BufferList == null)
1276 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
1279 SocketOperation op = (e.Buffer != null) ? SocketOperation.Receive : SocketOperation.ReceiveGeneric;
1280 e.Worker.Init (this, e, op);
1281 SocketAsyncResult res = e.Worker.result;
1282 if (e.Buffer != null) {
1283 res.Buffer = e.Buffer;
1284 res.Offset = e.Offset;
1287 res.Buffers = e.BufferList;
1289 res.SockFlags = e.SocketFlags;
1292 readQ.Enqueue (e.Worker);
1293 count = readQ.Count;
1296 // Receive takes care of ReceiveGeneric
1297 socket_pool_queue (Worker.Dispatcher, res);
1303 public bool SendAsync (SocketAsyncEventArgs e)
1305 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1306 if (disposed && closed)
1307 throw new ObjectDisposedException (GetType ().ToString ());
1308 if (e.Buffer == null && e.BufferList == null)
1309 throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
1312 SocketOperation op = (e.Buffer != null) ? SocketOperation.Send : SocketOperation.SendGeneric;
1313 e.Worker.Init (this, e, op);
1314 SocketAsyncResult res = e.Worker.result;
1315 if (e.Buffer != null) {
1316 res.Buffer = e.Buffer;
1317 res.Offset = e.Offset;
1320 res.Buffers = e.BufferList;
1322 res.SockFlags = e.SocketFlags;
1325 writeQ.Enqueue (e.Worker);
1326 count = writeQ.Count;
1329 // Send takes care of SendGeneric
1330 socket_pool_queue (Worker.Dispatcher, res);
1335 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1336 extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
1338 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1339 private extern static int Receive_internal(IntPtr sock,
1346 internal int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
1349 int ret = Receive_internal (socket, buf, offset, size, flags, out nativeError);
1350 error = (SocketError) nativeError;
1351 if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
1361 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1362 private extern static void GetSocketOption_obj_internal(IntPtr socket,
1363 SocketOptionLevel level, SocketOptionName name, out object obj_val,
1366 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1367 private extern static int Send_internal(IntPtr sock,
1368 byte[] buf, int offset,
1373 internal int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
1376 error = SocketError.Success;
1382 int ret = Send_internal (socket, buf, offset, size, flags, out nativeError);
1384 error = (SocketError)nativeError;
1386 if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
1396 public object GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName)
1398 if (disposed && closed)
1399 throw new ObjectDisposedException (GetType ().ToString ());
1404 GetSocketOption_obj_internal (socket, optionLevel, optionName, out obj_val,
1407 throw new SocketException (error);
1409 if (optionName == SocketOptionName.Linger) {
1410 return((LingerOption)obj_val);
1411 } else if (optionName == SocketOptionName.AddMembership ||
1412 optionName == SocketOptionName.DropMembership) {
1413 return((MulticastOption)obj_val);
1414 } else if (obj_val is int) {
1415 return((int)obj_val);
1421 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1422 private extern static void Shutdown_internal (IntPtr socket, SocketShutdown how, out int error);
1424 public void Shutdown (SocketShutdown how)
1426 if (disposed && closed)
1427 throw new ObjectDisposedException (GetType ().ToString ());
1430 throw new SocketException (10057); // Not connected
1434 Shutdown_internal (socket, how, out error);
1436 throw new SocketException (error);
1439 [MethodImplAttribute(MethodImplOptions.InternalCall)]
1440 private extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level,
1441 SocketOptionName name, object obj_val,
1442 byte [] byte_val, int int_val,
1445 public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
1447 if (disposed && closed)
1448 throw new ObjectDisposedException (GetType ().ToString ());
1452 SetSocketOption_internal (socket, optionLevel, optionName, null,
1453 null, optionValue, out error);
1456 throw new SocketException (error);
1459 private void ThrowIfUpd ()
1461 #if !NET_2_1 || MOBILE
1462 if (protocol_type == ProtocolType.Udp)
1463 throw new SocketException ((int)SocketError.ProtocolOption);
1470 IAsyncResult BeginConnect(EndPoint end_point, AsyncCallback callback, object state)
1472 if (disposed && closed)
1473 throw new ObjectDisposedException (GetType ().ToString ());
1475 if (end_point == null)
1476 throw new ArgumentNullException ("end_point");
1478 SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
1479 req.EndPoint = end_point;
1481 // Bug #75154: Connect() should not succeed for .Any addresses.
1482 if (end_point is IPEndPoint) {
1483 IPEndPoint ep = (IPEndPoint) end_point;
1484 if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
1485 req.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
1491 if (connect_in_progress) {
1492 // This could happen when multiple IPs are used
1493 // Calling connect() again will reset the connection attempt and cause
1494 // an error. Better to just close the socket and move on.
1495 connect_in_progress = false;
1496 Close_internal (socket, out error);
1497 socket = Socket_internal (address_family, socket_type, protocol_type, out error);
1499 throw new SocketException (error);
1501 bool blk = blocking;
1504 SocketAddress serial = end_point.Serialize ();
1505 Connect_internal (socket, serial, out error);
1512 req.Complete (true);
1516 if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
1520 req.Complete (new SocketException (error), true);
1527 connect_in_progress = true;
1528 socket_pool_queue (Worker.Dispatcher, req);
1537 IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback callback, object state)
1540 if (disposed && closed)
1541 throw new ObjectDisposedException (GetType ().ToString ());
1543 if (addresses == null)
1544 throw new ArgumentNullException ("addresses");
1546 if (addresses.Length == 0)
1547 throw new ArgumentException ("Empty addresses list");
1549 if (this.AddressFamily != AddressFamily.InterNetwork &&
1550 this.AddressFamily != AddressFamily.InterNetworkV6)
1551 throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
1553 if (port <= 0 || port > 65535)
1554 throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
1557 throw new InvalidOperationException ();
1560 SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
1561 req.Addresses = addresses;
1564 return BeginMConnect (req);
1567 IAsyncResult BeginMConnect (SocketAsyncResult req)
1569 IAsyncResult ares = null;
1570 Exception exc = null;
1571 for (int i = req.CurrentAddress; i < req.Addresses.Length; i++) {
1572 IPAddress addr = req.Addresses [i];
1573 IPEndPoint ep = new IPEndPoint (addr, req.Port);
1575 req.CurrentAddress++;
1576 ares = BeginConnect (ep, null, req);
1577 if (ares.IsCompleted && ares.CompletedSynchronously) {
1578 ((SocketAsyncResult) ares).CheckIfThrowDelayedException ();
1579 req.DoMConnectCallback ();
1582 } catch (Exception e) {
1594 // Returns false when it is ok to use RemoteEndPoint
1595 // true when addresses must be used (and addresses could be null/empty)
1596 bool GetCheckedIPs (SocketAsyncEventArgs e, out IPAddress [] addresses)
1599 #if MOONLIGHT || NET_4_0
1600 // Connect to the first address that match the host name, like:
1601 // http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
1602 // while skipping entries that do not match the address family
1603 DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
1605 addresses = Dns.GetHostAddresses (dep.Host);
1606 IPEndPoint endpoint;
1607 #if MOONLIGHT && !INSIDE_SYSTEM
1608 if (!e.PolicyRestricted && !SecurityManager.HasElevatedPermissions) {
1609 List<IPAddress> valid = new List<IPAddress> ();
1610 foreach (IPAddress a in addresses) {
1611 // if we're not downloading a socket policy then check the policy
1612 // and if we're not running with elevated permissions (SL4 OoB option)
1613 endpoint = new IPEndPoint (a, dep.Port);
1614 if (!CrossDomainPolicyManager.CheckEndPoint (endpoint, e.SocketClientAccessPolicyProtocol))
1618 if (valid.Count == 0)
1619 e.SocketError = SocketError.AccessDenied;
1620 addresses = valid.ToArray ();
1625 e.ConnectByNameError = null;
1626 #if MOONLIGHT && !INSIDE_SYSTEM
1627 if (!e.PolicyRestricted && !SecurityManager.HasElevatedPermissions) {
1628 if (CrossDomainPolicyManager.CheckEndPoint (e.RemoteEndPoint, e.SocketClientAccessPolicyProtocol))
1631 e.SocketError = SocketError.AccessDenied;
1636 return true; // do not use remote endpoint
1638 return false; // < NET_4_0 -> use remote endpoint
1642 bool ConnectAsyncReal (SocketAsyncEventArgs e)
1644 IPAddress [] addresses = null;
1645 bool use_remoteep = true;
1646 #if MOONLIGHT || NET_4_0
1647 use_remoteep = !GetCheckedIPs (e, out addresses);
1648 bool policy_failed = (e.SocketError == SocketError.AccessDenied);
1651 Worker w = e.Worker;
1652 w.Init (this, e, SocketOperation.Connect);
1653 SocketAsyncResult result = w.result;
1655 if (policy_failed) {
1656 // SocketAsyncEventArgs.Completed must be called
1658 result.EndPoint = e.RemoteEndPoint;
1659 result.error = (int) SocketError.AccessDenied;
1661 socket_pool_queue (Worker.Dispatcher, result);
1665 IAsyncResult ares = null;
1668 result.EndPoint = e.RemoteEndPoint;
1669 ares = BeginConnect (e.RemoteEndPoint, SocketAsyncEventArgs.Dispatcher, e);
1671 #if MOONLIGHT || NET_4_0
1674 DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
1675 result.Addresses = addresses;
1676 result.Port = dep.Port;
1678 ares = BeginConnect (addresses, dep.Port, SocketAsyncEventArgs.Dispatcher, e);
1681 if (ares.IsCompleted && ares.CompletedSynchronously) {
1682 ((SocketAsyncResult) ares).CheckIfThrowDelayedException ();
1685 } catch (Exception exc) {
1686 result.Complete (exc, true);
1693 public bool ConnectAsync (SocketAsyncEventArgs e)
1695 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1696 if (disposed && closed)
1697 throw new ObjectDisposedException (GetType ().ToString ());
1699 throw new InvalidOperationException ("You may not perform this operation after calling the Listen method.");
1700 if (e.RemoteEndPoint == null)
1701 throw new ArgumentNullException ("remoteEP");
1703 return ConnectAsyncReal (e);
1707 static void CheckConnect (SocketAsyncEventArgs e)
1709 // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
1711 if (e.RemoteEndPoint == null)
1712 throw new ArgumentNullException ("remoteEP");
1713 if (e.BufferList != null)
1714 throw new ArgumentException ("Multiple buffers cannot be used with this method.");
1717 public bool ConnectAsync (SocketAsyncEventArgs e)
1719 if (disposed && closed)
1720 throw new ObjectDisposedException (GetType ().ToString ());
1723 // if an address family is specified then they must match
1724 AddressFamily raf = e.RemoteEndPoint.AddressFamily;
1725 if ((raf != AddressFamily.Unspecified) && (raf != AddressFamily))
1726 throw new NotSupportedException ("AddressFamily mismatch between socket and endpoint");
1728 // connected, not yet connected or even policy denied, the Socket.RemoteEndPoint is always
1729 // available after the ConnectAsync call
1730 seed_endpoint = e.RemoteEndPoint;
1731 return ConnectAsyncReal (e);
1734 public static bool ConnectAsync (SocketType socketType, ProtocolType protocolType, SocketAsyncEventArgs e)
1736 // exception ordering requires to check before creating the socket (good thing resource wise too)
1739 // create socket based on the endpoint address family (if specified), otherwise default fo IPv4
1740 AddressFamily raf = e.RemoteEndPoint.AddressFamily;
1741 if (raf == AddressFamily.Unspecified)
1742 raf = AddressFamily.InterNetwork;
1743 Socket s = new Socket (raf, socketType, protocolType);
1744 return s.ConnectAsyncReal (e);
1747 public static void CancelConnectAsync (SocketAsyncEventArgs e)
1750 throw new ArgumentNullException ("e");
1752 // FIXME: this is canceling a synchronous connect, not an async one
1753 Socket s = e.ConnectSocket;
1754 if ((s != null) && (s.blocking_thread != null))
1755 s.blocking_thread.Abort ();
1758 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1759 private extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
1765 int Receive (IList<ArraySegment<byte>> buffers)
1769 ret = Receive (buffers, SocketFlags.None, out error);
1770 if (error != SocketError.Success) {
1771 throw new SocketException ((int)error);
1776 [CLSCompliant (false)]
1782 int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1786 ret = Receive (buffers, socketFlags, out error);
1787 if (error != SocketError.Success) {
1788 throw new SocketException ((int)error);
1793 [CLSCompliant (false)]
1799 int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1801 if (disposed && closed)
1802 throw new ObjectDisposedException (GetType ().ToString ());
1804 if (buffers == null ||
1805 buffers.Count == 0) {
1806 throw new ArgumentNullException ("buffers");
1809 int numsegments = buffers.Count;
1813 /* Only example I can find of sending a byte
1814 * array reference directly into an internal
1816 * System.Runtime.Remoting/System.Runtime.Remoting.Channels.Ipc.Win32/NamedPipeSocket.cs,
1817 * so taking a lead from that...
1819 WSABUF[] bufarray = new WSABUF[numsegments];
1820 GCHandle[] gch = new GCHandle[numsegments];
1822 for(int i = 0; i < numsegments; i++) {
1823 ArraySegment<byte> segment = buffers[i];
1825 if (segment.Offset < 0 || segment.Count < 0 ||
1826 segment.Count > segment.Array.Length - segment.Offset)
1827 throw new ArgumentOutOfRangeException ("segment");
1829 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
1830 bufarray[i].len = segment.Count;
1831 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
1835 ret = Receive_internal (socket, bufarray,
1839 for(int i = 0; i < numsegments; i++) {
1840 if (gch[i].IsAllocated) {
1846 errorCode = (SocketError)nativeError;
1850 [MethodImplAttribute (MethodImplOptions.InternalCall)]
1851 private extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
1857 int Send (IList<ArraySegment<byte>> buffers)
1861 ret = Send (buffers, SocketFlags.None, out error);
1862 if (error != SocketError.Success) {
1863 throw new SocketException ((int)error);
1873 int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
1877 ret = Send (buffers, socketFlags, out error);
1878 if (error != SocketError.Success) {
1879 throw new SocketException ((int)error);
1884 [CLSCompliant (false)]
1890 int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
1892 if (disposed && closed)
1893 throw new ObjectDisposedException (GetType ().ToString ());
1894 if (buffers == null)
1895 throw new ArgumentNullException ("buffers");
1896 if (buffers.Count == 0)
1897 throw new ArgumentException ("Buffer is empty", "buffers");
1898 int numsegments = buffers.Count;
1902 WSABUF[] bufarray = new WSABUF[numsegments];
1903 GCHandle[] gch = new GCHandle[numsegments];
1904 for(int i = 0; i < numsegments; i++) {
1905 ArraySegment<byte> segment = buffers[i];
1907 if (segment.Offset < 0 || segment.Count < 0 ||
1908 segment.Count > segment.Array.Length - segment.Offset)
1909 throw new ArgumentOutOfRangeException ("segment");
1911 gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
1912 bufarray[i].len = segment.Count;
1913 bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
1917 ret = Send_internal (socket, bufarray, socketFlags, out nativeError);
1919 for(int i = 0; i < numsegments; i++) {
1920 if (gch[i].IsAllocated) {
1925 errorCode = (SocketError)nativeError;
1929 Exception InvalidAsyncOp (string method)
1931 return new InvalidOperationException (method + " can only be called once per asynchronous operation");
1939 int EndReceive (IAsyncResult result)
1942 int bytesReceived = EndReceive (result, out error);
1943 if (error != SocketError.Success) {
1944 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
1946 throw new SocketException ((int)error);
1948 return bytesReceived;
1956 int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
1958 if (disposed && closed)
1959 throw new ObjectDisposedException (GetType ().ToString ());
1961 if (asyncResult == null)
1962 throw new ArgumentNullException ("asyncResult");
1964 SocketAsyncResult req = asyncResult as SocketAsyncResult;
1966 throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
1968 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
1969 throw InvalidAsyncOp ("EndReceive");
1970 if (!asyncResult.IsCompleted)
1971 asyncResult.AsyncWaitHandle.WaitOne ();
1973 errorCode = req.ErrorCode;
1974 // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
1975 // kinds of exceptions that should be thrown.
1976 if (errorCode == SocketError.Success)
1977 req.CheckIfThrowDelayedException();
1987 int EndSend (IAsyncResult result)
1990 int bytesSent = EndSend (result, out error);
1991 if (error != SocketError.Success) {
1992 if (error != SocketError.WouldBlock && error != SocketError.InProgress)
1994 throw new SocketException ((int)error);
2004 int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
2006 if (disposed && closed)
2007 throw new ObjectDisposedException (GetType ().ToString ());
2008 if (asyncResult == null)
2009 throw new ArgumentNullException ("asyncResult");
2011 SocketAsyncResult req = asyncResult as SocketAsyncResult;
2013 throw new ArgumentException ("Invalid IAsyncResult", "result");
2015 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
2016 throw InvalidAsyncOp ("EndSend");
2017 if (!asyncResult.IsCompleted)
2018 asyncResult.AsyncWaitHandle.WaitOne ();
2020 errorCode = req.ErrorCode;
2021 // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
2022 // kinds of exceptions that should be thrown.
2023 if (errorCode == SocketError.Success)
2024 req.CheckIfThrowDelayedException ();
2029 // Used by Udpclient
2035 int EndReceiveFrom(IAsyncResult result, ref EndPoint end_point)
2037 if (disposed && closed)
2038 throw new ObjectDisposedException (GetType ().ToString ());
2041 throw new ArgumentNullException ("result");
2043 if (end_point == null)
2044 throw new ArgumentNullException ("remote_end");
2046 SocketAsyncResult req = result as SocketAsyncResult;
2048 throw new ArgumentException ("Invalid IAsyncResult", "result");
2050 if (Interlocked.CompareExchange (ref req.EndCalled, 1, 0) == 1)
2051 throw InvalidAsyncOp ("EndReceiveFrom");
2052 if (!result.IsCompleted)
2053 result.AsyncWaitHandle.WaitOne();
2055 req.CheckIfThrowDelayedException();
2056 end_point = req.EndPoint;
2060 [MethodImplAttribute(MethodImplOptions.InternalCall)]
2061 static extern void socket_pool_queue (SocketAsyncCall d, SocketAsyncResult r);