f4586a253f8ce09c2b2178d6f5e08ad53b55445a
[mono.git] / mcs / class / System / Test / System.Net.Sockets / SocketTest.cs
1 // System.Net.Sockets.SocketTest.cs
2 //
3 // Authors:
4 //    Brad Fitzpatrick (brad@danga.com)
5 //    Gonzalo Paniagua Javier (gonzalo@novell.com)
6 //
7 // (C) Copyright 2003 Brad Fitzpatrick
8 // Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
9 //
10
11 using System;
12 using System.Diagnostics;
13 using System.Linq;
14 using System.Collections;
15 using System.Threading;
16 using System.Reflection;
17 using System.Text.RegularExpressions;
18 using System.Threading.Tasks;
19 using System.Net;
20 using System.Net.Sockets;
21 using NUnit.Framework;
22 using System.IO;
23
24 using System.Collections.Generic;
25
26 using MonoTests.Helpers;
27
28 namespace MonoTests.System.Net.Sockets
29 {
30         [TestFixture]
31         public class SocketTest
32         {
33                 // note: also used in SocketCas tests
34                 public const string BogusAddress = "192.168.244.244";
35                 public const int BogusPort = 23483;
36
37                 [Test]
38                 public void ConnectIPAddressAny ()
39                 {
40                         IPEndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
41
42                         /* UDP sockets use Any to disconnect
43                         try {
44                                 using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
45                                         s.Connect (ep);
46                                         s.Close ();
47                                 }
48                                 Assert.Fail ("#1");
49                         } catch (SocketException ex) {
50                                 Assert.AreEqual (10049, ex.ErrorCode, "#2");
51                         }
52                         */
53
54                         try {
55                                 using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
56                                         s.Connect (ep);
57                                         s.Close ();
58                                 }
59                                 Assert.Fail ("#3");
60                         } catch (SocketException ex) {
61                                 Assert.AreEqual (10049, ex.ErrorCode, "#4");
62                         }
63                 }
64
65                 [Test]
66                 [Ignore ("Bug #75158")] // Looks like MS fails after the .ctor, when you try to use the socket
67                 public void IncompatibleAddress ()
68                 {
69                         IPEndPoint epIPv6 = new IPEndPoint (IPAddress.IPv6Any,
70                                                                 NetworkHelpers.FindFreePort ());
71
72                         try {
73                                 using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)) {
74                                         s.Connect (epIPv6);
75                                         s.Close ();
76                                 }
77                                 Assert.Fail ("#1");
78                         } catch (SocketException ex) {
79                                 // address incompatible with protocol
80                                 int expectedError = 10047;
81                                 Assert.AreEqual (expectedError, ex.ErrorCode,
82                                                 "#2");
83                         }
84                 }
85
86                 [Test]
87                 [Category ("InetAccess")]
88                 public void BogusEndConnect ()
89                 {
90                         IPAddress ipOne = IPAddress.Parse (BogusAddress);
91                         IPEndPoint ipEP = new IPEndPoint (ipOne, BogusPort);
92                         Socket sock = new Socket (ipEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
93                         IAsyncResult ar = sock.BeginConnect (ipEP, null, null);
94
95                         try {
96                                 // should raise an exception because connect was bogus
97                                 sock.EndConnect (ar);
98                                 Assert.Fail ("#1");
99                         } catch (SocketException ex) {
100                                 // Actual error code depends on network configuration.
101                                 var error = (SocketError) ex.ErrorCode;
102                                 Assert.That (error == SocketError.TimedOut ||
103                                              error == SocketError.ConnectionRefused ||
104                                              error == SocketError.NetworkUnreachable ||
105                                              error == SocketError.HostUnreachable, "#2");
106                         }
107                 }
108
109                 [Test]
110                 [ExpectedException (typeof (ArgumentNullException))]
111                 public void SelectEmpty ()
112                 {
113                         ArrayList list = new ArrayList ();
114                         Socket.Select (list, list, list, 1000);
115                 }
116                 
117                 private bool BlockingConnect (bool block, int port)
118                 {
119                         IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, port);
120                         Socket server = new Socket(AddressFamily.InterNetwork,
121                                                    SocketType.Stream,
122                                                    ProtocolType.Tcp);
123                         server.Bind(ep);
124                         server.Blocking=block;
125
126                         server.Listen(0);
127
128                         Socket conn = new Socket (AddressFamily.InterNetwork,
129                                                   SocketType.Stream,
130                                                   ProtocolType.Tcp);
131                         conn.Connect (ep);
132
133                         Socket client = null;
134                         var sw = Stopwatch.StartNew ();
135                         while (sw.ElapsedMilliseconds < 100)
136                         {
137                                 try {
138                                         client = server.Accept();
139                                         break;
140                                 }
141                                 catch (SocketException ex) {
142                                         if (ex.SocketErrorCode == SocketError.WouldBlock)
143                                                 continue;
144                                         throw;
145                                 }
146                         }
147                         Assert.IsNotNull (client, "Couldn't accept a client connection within 100ms.");
148                         bool client_block = client.Blocking;
149
150                         client.Close();
151                         conn.Close();
152                         server.Close();
153                         
154                         return(client_block);
155                 }
156
157                 [Test]
158                 public void AcceptBlockingStatus()
159                 {
160                         bool block;
161                         var port = NetworkHelpers.FindFreePort ();
162         
163                         block = BlockingConnect(true, port);
164                         Assert.AreEqual (block, true, "BlockingStatus01");
165
166                         block = BlockingConnect(false, port);
167                         Assert.AreEqual (block, false, "BlockingStatus02");
168                 }
169
170                 static bool CFAConnected = false;
171                 static ManualResetEvent CFACalledBack;
172                 
173                 private static void CFACallback (IAsyncResult asyncResult)
174                 {
175                         Socket sock = (Socket)asyncResult.AsyncState;
176                         CFAConnected = sock.Connected;
177                         
178                         if (sock.Connected) {
179                                 sock.EndConnect (asyncResult);
180                         }
181
182                         CFACalledBack.Set ();
183                 }
184
185                 [Test] // Connect (IPEndPoint)
186                 public void Connect1_RemoteEP_Null ()
187                 {
188                         Socket s = new Socket (AddressFamily.InterNetwork,
189                                 SocketType.Stream, ProtocolType.Tcp);
190                         try {
191                                 s.Connect ((IPEndPoint) null);
192                                 Assert.Fail ("#1");
193                         } catch (ArgumentNullException ex) {
194                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
195                                 Assert.IsNull (ex.InnerException, "#3");
196                                 Assert.IsNotNull (ex.Message, "#4");
197                                 Assert.AreEqual ("remoteEP", ex.ParamName, "#5");
198                         }
199                 }
200
201                 [Test]
202                 public void ConnectFailAsync ()
203                 {
204                         Socket sock = new Socket (AddressFamily.InterNetwork,
205                                                   SocketType.Stream,
206                                                   ProtocolType.Tcp);
207                         sock.Blocking = false;
208                         CFACalledBack = new ManualResetEvent (false);
209                         CFACalledBack.Reset ();
210
211                         /* Need a port that is not being used for
212                          * anything...
213                          */
214                         sock.BeginConnect (new IPEndPoint (IPAddress.Loopback,
215                                                            NetworkHelpers.FindFreePort ()),
216                                            new AsyncCallback (CFACallback),
217                                            sock);
218                         CFACalledBack.WaitOne ();
219
220                         Assert.AreEqual (CFAConnected, false, "ConnectFail");
221                 }
222                 
223                 [Test]
224                 public void SetSocketOptionBoolean ()
225                 {
226                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
227                         Socket sock = new Socket (ep.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
228                         try {
229                                 sock.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
230                         } finally {
231                                 sock.Close ();
232                         }
233                 }
234                 [Test]
235                 public void TestSelect1 ()
236                 {
237                         Socket srv = CreateServer (NetworkHelpers.FindFreePort ());
238                         ClientSocket clnt = new ClientSocket (srv.LocalEndPoint);
239                         Thread th = new Thread (new ThreadStart (clnt.ConnectSleepClose));
240                         Socket acc = null;
241                         try {
242                                 th.Start ();
243                                 acc = srv.Accept ();
244                                 clnt.Write ();
245                                 ArrayList list = new ArrayList ();
246                                 ArrayList empty = new ArrayList ();
247                                 list.Add (acc);
248                                 Socket.Select (list, empty, empty, 100);
249                                 Assert.AreEqual (0, empty.Count, "#01");
250                                 Assert.AreEqual (1, list.Count, "#02");
251                                 Socket.Select (empty, list, empty, 100);
252                                 Assert.AreEqual (0, empty.Count, "#03");
253                                 Assert.AreEqual (1, list.Count, "#04");
254                                 Socket.Select (list, empty, empty, -1);
255                                 Assert.AreEqual (0, empty.Count, "#05");
256                                 Assert.AreEqual (1, list.Count, "#06");
257                                 // Need to read the 10 bytes from the client to avoid a RST
258                                 byte [] bytes = new byte [10];
259                                 acc.Receive (bytes);
260                         } finally {
261                                 if (acc != null)
262                                         acc.Close ();
263                                 srv.Close ();
264                         }
265                 }
266
267                 static Socket CreateServer (int port)
268                 {
269                         Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
270                         sock.Bind (new IPEndPoint (IPAddress.Loopback, port));
271                         sock.Listen (1);
272                         return sock;
273                 }
274
275                 class ClientSocket {
276                         Socket sock;
277                         EndPoint ep;
278
279                         public ClientSocket (EndPoint ep)
280                         {
281                                 this.ep = ep;
282                                 sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
283                         }
284
285                         public void ConnectSleepClose ()
286                         {
287                                 sock.Connect (ep);
288                                 Thread.Sleep (2000);
289                                 sock.Close ();
290                         }
291
292                         public void Write ()
293                         {
294                                 byte [] b = new byte [10];
295                                 sock.Send (b);
296                         }
297                 }
298
299                 byte[] buf = new byte[100];
300
301                 [Test]
302                 [ExpectedException (typeof (ObjectDisposedException))]
303                 public void Disposed2 ()
304                 {
305                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
306                         s.Close();
307
308                         s.Blocking = true;
309                 }
310
311                 [Test]
312                 [ExpectedException (typeof (ObjectDisposedException))]
313                 public void Disposed6 ()
314                 {
315                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
316                         s.Close();
317
318                         s.Listen (5);
319                 }
320
321                 [Test]
322                 [ExpectedException (typeof (ObjectDisposedException))]
323                 public void Disposed7 ()
324                 {
325                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
326                         s.Close();
327
328                         s.Poll (100, 0);
329                 }
330
331                 [Test]
332                 [ExpectedException (typeof (ObjectDisposedException))]
333                 public void Disposed15 ()
334                 {
335                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
336                         s.Close();
337
338                         s.Send (buf);
339                 }
340
341                 [Test]
342                 [ExpectedException (typeof (ObjectDisposedException))]
343                 public void Disposed16 ()
344                 {
345                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
346                         s.Close();
347
348                         s.Send (buf, 0);
349                 }
350
351                 [Test]
352                 [ExpectedException (typeof (ObjectDisposedException))]
353                 public void Disposed17 ()
354                 {
355                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
356                         s.Close();
357
358                         s.Send (buf, 10, 0);
359                 }
360
361                 [Test]
362                 [ExpectedException (typeof (ObjectDisposedException))]
363                 public void Disposed18 ()
364                 {
365                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
366                         s.Close();
367
368                         s.Send (buf, 0, 10, 0);
369                 }
370
371                 [Test]
372                 [ExpectedException (typeof (ObjectDisposedException))]
373                 public void Disposed19 ()
374                 {
375                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
376                         EndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
377                         s.Close();
378
379                         s.SendTo (buf, 0, ep);
380                 }
381
382                 [Test]
383                 [ExpectedException (typeof (ObjectDisposedException))]
384                 public void Disposed20 ()
385                 {
386                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
387                         EndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
388                         s.Close();
389
390                         s.SendTo (buf, 10, 0, ep);
391                 }
392
393                 [Test]
394                 [ExpectedException (typeof (ObjectDisposedException))]
395                 public void Disposed21 ()
396                 {
397                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
398                         EndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
399                         s.Close();
400
401                         s.SendTo (buf, 0, 10, 0, ep);
402                 }
403
404                 [Test]
405                 [ExpectedException (typeof (ObjectDisposedException))]
406                 public void Disposed22 ()
407                 {
408                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
409                         EndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
410                         s.Close();
411
412                         s.SendTo (buf, ep);
413                 }
414
415                 [Test]
416                 [ExpectedException (typeof (ObjectDisposedException))]
417                 public void Disposed23 ()
418                 {
419                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
420                         s.Close();
421
422                         s.Shutdown (0);
423                 }
424
425                 [Test]
426                 public void GetHashCodeTest ()
427                 {
428                         Socket server = new Socket (AddressFamily.InterNetwork,
429                                 SocketType.Stream, ProtocolType.Tcp);
430                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
431                                                         NetworkHelpers.FindFreePort ());
432                         server.Bind (ep);
433                         server.Listen (1);
434
435                         Socket client = new Socket (AddressFamily.InterNetwork, 
436                                 SocketType.Stream, ProtocolType.Tcp);
437                         int hashcodeA = client.GetHashCode ();
438                         client.Connect (ep);
439                         int hashcodeB = client.GetHashCode ();
440                         Assert.AreEqual (hashcodeA, hashcodeB, "#1");
441                         client.Close ();
442                         int hashcodeC = client.GetHashCode ();
443                         Assert.AreEqual (hashcodeB, hashcodeC, "#2");
444                         server.Close ();
445                 }
446
447                 static ManualResetEvent SocketError_event = new ManualResetEvent (false);
448
449                 private static void SocketError_callback (IAsyncResult ar)
450                 {
451                         Socket sock = (Socket)ar.AsyncState;
452                         
453                         if(sock.Connected) {
454                                 sock.EndConnect (ar);
455                         }
456
457                         SocketError_event.Set ();
458                 }
459
460                 [Test]
461                 public void SocketErrorTest ()
462                 {
463                         Socket sock = new Socket (AddressFamily.InterNetwork,
464                                                   SocketType.Stream,
465                                                   ProtocolType.Tcp);
466                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
467                                                         BogusPort);
468                         
469                         SocketError_event.Reset ();
470
471                         sock.Blocking = false;
472                         sock.BeginConnect (ep, new AsyncCallback(SocketError_callback),
473                                 sock);
474
475                         if (SocketError_event.WaitOne (2000, false) == false) {
476                                 Assert.Fail ("SocketError wait timed out");
477                         }
478
479                         Assert.AreEqual (false, sock.Connected, "SocketError #1");
480
481                         int error;
482
483                         error = (int)sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
484                         Assert.AreEqual (10061, error, "SocketError #2");
485
486                         error = (int)sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
487                         Assert.AreEqual (10061, error, "SocketError #3");
488
489                         sock.Close ();
490                 }
491                 
492
493                 [Test]
494                 public void SocketInformationCtor ()
495                 {
496                 }
497                 
498                 [Test]
499                 public void DontFragmentDefaultTcp ()
500                 {
501                         Socket sock = new Socket (AddressFamily.InterNetwork,
502                                                   SocketType.Stream,
503                                                   ProtocolType.Tcp);
504                         
505                         Assert.AreEqual (false, sock.DontFragment, "DontFragmentDefaultTcp");
506
507                         sock.Close ();
508                 }
509
510                 [Test]
511                 [Category ("NotWorking")] // DontFragment doesn't work
512                 public void DontFragmentChangeTcp ()
513                 {
514                         Socket sock = new Socket (AddressFamily.InterNetwork,
515                                                   SocketType.Stream,
516                                                   ProtocolType.Tcp);
517                         
518                         sock.DontFragment = true;
519                         
520                         Assert.AreEqual (true, sock.DontFragment, "DontFragmentChangeTcp");
521
522                         sock.Close ();
523                 }
524                 
525                 [Test]
526                 public void DontFragmentDefaultUdp ()
527                 {
528                         Socket sock = new Socket (AddressFamily.InterNetwork,
529                                                   SocketType.Dgram,
530                                                   ProtocolType.Udp);
531                         
532                         Assert.AreEqual (false, sock.DontFragment, "DontFragmentDefaultUdp");
533
534                         sock.Close ();
535                 }
536
537                 [Test]
538                 [Category ("NotWorking")] // DontFragment doesn't work
539                 public void DontFragmentChangeUdp ()
540                 {
541                         Socket sock = new Socket (AddressFamily.InterNetwork,
542                                                   SocketType.Dgram,
543                                                   ProtocolType.Udp);
544                         
545                         sock.DontFragment = true;
546                         
547                         Assert.AreEqual (true, sock.DontFragment, "DontFragmentChangeUdp");
548
549                         sock.Close ();
550                 }
551
552                 [Test]
553                 [ExpectedException (typeof(ObjectDisposedException))]
554                 public void DontFragmentClosed ()
555                 {
556                         Socket sock = new Socket (AddressFamily.InterNetwork,
557                                                   SocketType.Stream,
558                                                   ProtocolType.Tcp);
559                         
560                         sock.Close ();
561                         
562                         bool val = sock.DontFragment;
563                 }
564                 
565                 [Test]
566                 [Category ("NotWorking")] // Need to pick a non-IP AddressFamily that "works" on both mono and ms, this one only works on ms
567                 public void DontFragment ()
568                 {
569                         Socket sock = new Socket (AddressFamily.NetBios,
570                                                   SocketType.Seqpacket,
571                                                   ProtocolType.Unspecified);
572                         
573                         try {
574                                 sock.DontFragment = true;
575                                 Assert.Fail ("DontFragment #1");
576                         } catch (NotSupportedException) {
577                         } finally {
578                                 sock.Close ();
579                         }
580                 }
581                 
582                 [Test]
583                 public void EnableBroadcastDefaultTcp ()
584                 {
585                         Socket sock = new Socket (AddressFamily.InterNetwork,
586                                                   SocketType.Stream,
587                                                   ProtocolType.Tcp);
588                         
589                         try {
590                                 bool value = sock.EnableBroadcast;
591                                 Assert.Fail ("EnableBroadcastDefaultTcp #1");
592                         } catch (SocketException ex) {
593                                 Assert.AreEqual (10042, ex.ErrorCode, "EnableBroadcastDefaultTcp #2");
594                         } finally {
595                                 sock.Close ();
596                         }
597                 }
598
599                 [Test]
600                 public void EnableBroadcastDefaultUdp ()
601                 {
602                         Socket sock = new Socket (AddressFamily.InterNetwork,
603                                                   SocketType.Dgram,
604                                                   ProtocolType.Udp);
605                         
606                         Assert.AreEqual (false, sock.EnableBroadcast, "EnableBroadcastDefaultUdp");
607
608                         sock.Close ();
609                 }
610                 
611                 [Test]
612                 public void EnableBroadcastChangeTcp ()
613                 {
614                         Socket sock = new Socket (AddressFamily.InterNetwork,
615                                                   SocketType.Stream,
616                                                   ProtocolType.Tcp);
617                         
618                         try {
619                                 sock.EnableBroadcast = true;
620                                 Assert.Fail ("EnableBroadcastChangeTcp #1");
621                         } catch (SocketException ex) {
622                                 Assert.AreEqual (10042, ex.ErrorCode, "EnableBroadcastChangeTcp #2");
623                         } finally {
624                                 sock.Close ();
625                         }
626                 }
627                 
628                 [Test]
629                 public void EnableBroadcastChangeUdp ()
630                 {
631                         Socket sock = new Socket (AddressFamily.InterNetwork,
632                                                   SocketType.Dgram,
633                                                   ProtocolType.Udp);
634                         
635                         sock.EnableBroadcast = true;
636                         
637                         Assert.AreEqual (true, sock.EnableBroadcast, "EnableBroadcastChangeUdp");
638
639                         sock.Close ();
640                 }
641
642                 [Test]
643                 [ExpectedException (typeof(ObjectDisposedException))]
644                 public void EnableBroadcastClosed ()
645                 {
646                         Socket sock = new Socket (AddressFamily.InterNetwork,
647                                                   SocketType.Dgram,
648                                                   ProtocolType.Udp);
649                         
650                         sock.Close ();
651                         
652                         bool val = sock.EnableBroadcast;
653                 }
654
655                 /* Can't test the default for ExclusiveAddressUse as
656                  * it's different on different versions and service
657                  * packs of windows
658                  */
659                 [Test]
660                 [Category ("NotWorking")] // Not supported on Linux
661                 public void ExclusiveAddressUseUnbound ()
662                 {
663                         Socket sock = new Socket (AddressFamily.InterNetwork,
664                                                   SocketType.Stream,
665                                                   ProtocolType.Tcp);
666                         
667                         sock.ExclusiveAddressUse = true;
668                         
669                         Assert.AreEqual (true, sock.ExclusiveAddressUse, "ExclusiveAddressUseUnbound");
670                         
671                         sock.Close ();
672                 }
673
674                 [Test]
675                 [ExpectedException (typeof(InvalidOperationException))]
676                 [Category ("NotWorking")] // Not supported on Linux
677                 public void ExclusiveAddressUseBound ()
678                 {
679                         Socket sock = new Socket (AddressFamily.InterNetwork,
680                                                   SocketType.Stream,
681                                                   ProtocolType.Tcp);
682                         
683                         sock.Bind (new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ()));
684                         sock.ExclusiveAddressUse = true;
685                         sock.Close ();
686                 }
687
688                 [Test]
689                 [ExpectedException (typeof(ObjectDisposedException))]
690                 public void ExclusiveAddressUseClosed ()
691                 {
692                         Socket sock = new Socket (AddressFamily.InterNetwork,
693                                                   SocketType.Stream,
694                                                   ProtocolType.Tcp);
695                         
696                         sock.Close ();
697                         
698                         bool val = sock.ExclusiveAddressUse;
699                 }
700                 
701                 [Test]
702                 public void IsBoundTcp ()
703                 {
704                         Socket sock = new Socket (AddressFamily.InterNetwork,
705                                                   SocketType.Stream,
706                                                   ProtocolType.Tcp);
707                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
708                                                         BogusPort);
709                         
710                         Assert.AreEqual (false, sock.IsBound, "IsBoundTcp #1");
711                         
712                         sock.Bind (ep);
713                         Assert.AreEqual (true, sock.IsBound, "IsBoundTcp #2");
714
715                         sock.Listen (1);
716                         
717                         Socket sock2 = new Socket (AddressFamily.InterNetwork,
718                                                    SocketType.Stream,
719                                                    ProtocolType.Tcp);
720                         
721                         Assert.AreEqual (false, sock2.IsBound, "IsBoundTcp #3");
722                         
723                         sock2.Connect (ep);
724                         Assert.AreEqual (true, sock2.IsBound, "IsBoundTcp #4");
725                         
726                         sock2.Close ();
727                         Assert.AreEqual (true, sock2.IsBound, "IsBoundTcp #5");
728
729                         sock.Close ();
730                         Assert.AreEqual (true, sock.IsBound, "IsBoundTcp #6");
731                 }
732
733                 [Test]
734                 public void IsBoundUdp ()
735                 {
736                         Socket sock = new Socket (AddressFamily.InterNetwork,
737                                                   SocketType.Dgram,
738                                                   ProtocolType.Udp);
739                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
740                                                         BogusPort);
741                         
742                         Assert.AreEqual (false, sock.IsBound, "IsBoundUdp #1");
743                         
744                         sock.Bind (ep);
745                         Assert.AreEqual (true, sock.IsBound, "IsBoundUdp #2");
746                         
747                         sock.Close ();
748                         Assert.AreEqual (true, sock.IsBound, "IsBoundUdp #3");
749                         
750
751                         sock = new Socket (AddressFamily.InterNetwork,
752                                            SocketType.Dgram,
753                                            ProtocolType.Udp);
754                         
755                         Assert.AreEqual (false, sock.IsBound, "IsBoundUdp #4");
756                         
757                         sock.Connect (ep);
758                         Assert.AreEqual (true, sock.IsBound, "IsBoundUdp #5");
759                         
760                         sock.Close ();
761                         Assert.AreEqual (true, sock.IsBound, "IsBoundUdp #6");
762                 }
763
764                 [Test]
765                 /* Should not throw an exception */
766                 public void IsBoundClosed ()
767                 {
768                         Socket sock = new Socket (AddressFamily.InterNetwork,
769                                                   SocketType.Stream,
770                                                   ProtocolType.Tcp);
771                         
772                         sock.Close ();
773                         
774                         bool val = sock.IsBound;
775                 }
776                 
777                 /* Nothing much to test for LingerState */
778                 
779                 [Test]
780                 public void MulticastLoopbackDefaultTcp ()
781                 {
782                         Socket sock = new Socket (AddressFamily.InterNetwork,
783                                                   SocketType.Stream,
784                                                   ProtocolType.Tcp);
785                         
786                         try {
787                                 bool value = sock.MulticastLoopback;
788                                 Assert.Fail ("MulticastLoopbackDefaultTcp #1");
789                         } catch (SocketException ex) {
790                                 Assert.AreEqual (10042, ex.ErrorCode, "MulticastLoopbackDefaultTcp #2");
791                         } finally {
792                                 sock.Close ();
793                         }
794                 }
795
796                 [Test]
797                 public void MulticastLoopbackChangeTcp ()
798                 {
799                         Socket sock = new Socket (AddressFamily.InterNetwork,
800                                                   SocketType.Stream,
801                                                   ProtocolType.Tcp);
802                         
803                         try {
804                                 sock.MulticastLoopback = false;
805                                 Assert.Fail ("MulticastLoopbackChangeTcp #1");
806                         } catch (SocketException ex) {
807                                 Assert.AreEqual (10042, ex.ErrorCode, "MulticastLoopbackChangeTcp #2");
808                         } finally {
809                                 sock.Close ();
810                         }
811                 }
812                 
813                 [Test]
814                 public void MulticastLoopbackDefaultUdp ()
815                 {
816                         Socket sock = new Socket (AddressFamily.InterNetwork,
817                                                   SocketType.Dgram,
818                                                   ProtocolType.Udp);
819                         
820                         Assert.AreEqual (true, sock.MulticastLoopback, "MulticastLoopbackDefaultUdp");
821                         
822                         sock.Close ();
823                 }
824                 
825                 [Test]
826                 public void MulticastLoopbackChangeUdp ()
827                 {
828                         Socket sock = new Socket (AddressFamily.InterNetwork,
829                                                   SocketType.Dgram,
830                                                   ProtocolType.Udp);
831                         
832                         sock.MulticastLoopback = false;
833                         
834                         Assert.AreEqual (false, sock.MulticastLoopback, "MulticastLoopbackChangeUdp");
835                         
836                         sock.Close ();
837                 }
838
839                 [Test]
840                 [ExpectedException (typeof(ObjectDisposedException))]
841                 public void MulticastLoopbackClosed ()
842                 {
843                         Socket sock = new Socket (AddressFamily.InterNetwork,
844                                                   SocketType.Stream,
845                                                   ProtocolType.Tcp);
846                         
847                         sock.Close ();
848                         
849                         bool val = sock.MulticastLoopback;
850                 }
851                 
852                 /* OSSupportsIPv6 depends on the environment */
853                 
854                 [Test]
855                 [Category("NotWorking")] // We have different defaults for perf reasons
856                 public void ReceiveBufferSizeDefault ()
857                 {
858                         Socket sock = new Socket (AddressFamily.InterNetwork,
859                                                   SocketType.Stream,
860                                                   ProtocolType.Tcp);
861                         
862                         Assert.AreEqual (8192, sock.ReceiveBufferSize, "ReceiveBufferSizeDefault");
863                         
864                         sock.Close ();
865                 }
866                 
867                 [Test]
868                 [Category("NotWorking")] // We have different defaults for perf reasons
869                 public void ReceiveBufferSizeDefaultUdp ()
870                 {
871                         Socket sock = new Socket (AddressFamily.InterNetwork,
872                                                   SocketType.Dgram,
873                                                   ProtocolType.Udp);
874                         
875                         Assert.AreEqual (8192, sock.ReceiveBufferSize, "ReceiveBufferSizeDefaultUdp");
876                         
877                         sock.Close ();
878                 }
879
880                 [Test]
881                 public void ReceiveBufferSizeChange ()
882                 {
883                         Socket sock = new Socket (AddressFamily.InterNetwork,
884                                                   SocketType.Stream,
885                                                   ProtocolType.Tcp);
886                         
887                         sock.ReceiveBufferSize = 16384;
888                         
889                         Assert.AreEqual (16384, sock.ReceiveBufferSize, "ReceiveBufferSizeChange");
890                         
891                         sock.Close ();
892                 }
893
894                 [Test]
895                 [Category("NotWorking")] // We cannot totally remove buffers (minimum is set to 256
896                 public void BuffersCheck_None ()
897                 {
898                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
899                                 int original = s.ReceiveBufferSize;
900                                 s.ReceiveBufferSize = 0;
901                                 Assert.AreEqual (0, s.ReceiveBufferSize, "ReceiveBufferSize " + original.ToString ());
902
903                                 original = s.SendBufferSize;
904                                 s.SendBufferSize = 0;
905                                 Assert.AreEqual (0, s.SendBufferSize, "SendBufferSize " + original.ToString ());
906                         }
907                 }
908
909                 [Test]
910                 [ExpectedException (typeof(ObjectDisposedException))]
911                 public void ReceiveBufferSizeClosed ()
912                 {
913                         Socket sock = new Socket (AddressFamily.InterNetwork,
914                                                   SocketType.Stream,
915                                                   ProtocolType.Tcp);
916                         
917                         sock.Close ();
918                         
919                         int val = sock.ReceiveBufferSize;
920                 }
921                 
922                 [Test]
923                 [Category("NotWorking")] // We have different defaults for perf reasons
924                 public void SendBufferSizeDefault ()
925                 {
926                         Socket sock = new Socket (AddressFamily.InterNetwork,
927                                                   SocketType.Stream,
928                                                   ProtocolType.Tcp);
929                         
930                         Assert.AreEqual (8192, sock.SendBufferSize, "SendBufferSizeDefault");
931                         
932                         sock.Close ();
933                 }
934                 
935                 [Test]
936                 [Category("NotWorking")] // We have different defaults for perf reasons
937                 public void SendBufferSizeDefaultUdp ()
938                 {
939                         Socket sock = new Socket (AddressFamily.InterNetwork,
940                                                   SocketType.Dgram,
941                                                   ProtocolType.Udp);
942                         
943                         Assert.AreEqual (8192, sock.SendBufferSize, "SendBufferSizeDefaultUdp");
944                         
945                         sock.Close ();
946                 }
947
948                 [Test]
949                 public void SendBufferSizeChange ()
950                 {
951                         Socket sock = new Socket (AddressFamily.InterNetwork,
952                                                   SocketType.Stream,
953                                                   ProtocolType.Tcp);
954                         
955                         sock.SendBufferSize = 16384;
956                         
957                         Assert.AreEqual (16384, sock.SendBufferSize, "SendBufferSizeChange");
958                         
959                         sock.Close ();
960                 }
961
962                 [Test]
963                 [ExpectedException (typeof(ObjectDisposedException))]
964                 public void SendBufferSizeClosed ()
965                 {
966                         Socket sock = new Socket (AddressFamily.InterNetwork,
967                                                   SocketType.Stream,
968                                                   ProtocolType.Tcp);
969                         
970                         sock.Close ();
971                         
972                         int val = sock.SendBufferSize;
973                 }
974                 
975                 /* No test for TTL default as it's platform dependent */
976                 [Test]
977                 public void TtlChange ()
978                 {
979                         Socket sock = new Socket (AddressFamily.InterNetwork,
980                                                   SocketType.Stream,
981                                                   ProtocolType.Tcp);
982                         
983                         sock.Ttl = 255;
984                         
985                         Assert.AreEqual (255, sock.Ttl, "TtlChange");
986                         
987                         sock.Close ();
988                 }
989
990                 [Test]
991                 public void TtlChangeOverflow ()
992                 {
993                         Socket sock = new Socket (AddressFamily.InterNetwork,
994                                                   SocketType.Stream,
995                                                   ProtocolType.Tcp);
996                         
997                         try {
998                                 sock.Ttl = 256;
999                                 Assert.Fail ("TtlChangeOverflow #1");
1000                         } catch (ArgumentOutOfRangeException ex) {
1001                                 Assert.AreEqual ("value", ex.ParamName,
1002                                                  "TtlChangeOverflow #2");
1003                         } finally {
1004                                 sock.Close ();
1005                         }
1006                 }
1007                 
1008 /* Apparently you can set TTL=0 on the ms runtime!!
1009                         try {
1010                                 sock.Ttl = 0;
1011                                 Assert.Fail ("TtlChangeOverflow #4");
1012                         } catch (SocketException ex) {
1013                                 Assert.AreEqual (10022, ex.ErrorCode,
1014                                                  "TtlChangeOverflow #5");
1015                         } finally {
1016                                 sock.Close ();
1017                         }
1018 */
1019
1020                 [Test]
1021                 [ExpectedException (typeof(ObjectDisposedException))]
1022                 public void TtlClosed ()
1023                 {
1024                         Socket sock = new Socket (AddressFamily.InterNetwork,
1025                                                   SocketType.Stream,
1026                                                   ProtocolType.Tcp);
1027                         
1028                         sock.Close ();
1029                         
1030                         int val = sock.Ttl;
1031                 }
1032                 
1033                 [Test]
1034                 public void UseOnlyOverlappedIODefault ()
1035                 {
1036                         Socket sock = new Socket (AddressFamily.InterNetwork,
1037                                                   SocketType.Stream,
1038                                                   ProtocolType.Tcp);
1039                         
1040                         Assert.AreEqual (false, sock.UseOnlyOverlappedIO, "UseOnlyOverlappedIODefault");
1041                         
1042                         sock.Close ();
1043                 }
1044
1045                 //
1046                 // We need this because the Linux kernel in certain configurations
1047                 // will end up rounding up the values passed on to the kernel
1048                 // for socket send/receive timeouts.
1049                 //
1050                 int Approximate (int target, int value)
1051                 {
1052                         int epsilon = 10;
1053                         
1054                         if (value > target-10 && value < target+10)
1055                                 return target;
1056                         return value;
1057                 }
1058                 
1059                 [Test]
1060                 public void UseOnlyOverlappedIOChange ()
1061                 {
1062                         Socket sock = new Socket (AddressFamily.InterNetwork,
1063                                                   SocketType.Stream,
1064                                                   ProtocolType.Tcp);
1065                         
1066                         sock.UseOnlyOverlappedIO = true;
1067                         
1068                         Assert.AreEqual (true, sock.UseOnlyOverlappedIO, "UseOnlyOverlappedIOChange");
1069                         
1070                         sock.Close ();
1071                 }
1072
1073                 [Test]
1074                 /* Should not throw an exception */
1075                 public void UseOnlyOverlappedIOClosed ()
1076                 {
1077                         Socket sock = new Socket (AddressFamily.InterNetwork,
1078                                                   SocketType.Stream,
1079                                                   ProtocolType.Tcp);
1080                         
1081                         sock.Close ();
1082                         
1083                         bool val = sock.UseOnlyOverlappedIO;
1084                 }
1085                 
1086                 [Test]
1087                 public void SendTimeoutDefault ()
1088                 {
1089                         Socket sock = new Socket (AddressFamily.InterNetwork,
1090                                                   SocketType.Stream,
1091                                                   ProtocolType.Tcp);
1092                         
1093                         Assert.AreEqual (0, sock.SendTimeout, "SendTimeoutDefault");
1094                         
1095                         sock.Close ();
1096                 }
1097
1098                 [Test]
1099                 public void SendTimeoutChange ()
1100                 {
1101                         Socket sock = new Socket (AddressFamily.InterNetwork,
1102                                                   SocketType.Stream,
1103                                                   ProtocolType.Tcp);
1104                         
1105                         /* Should be rounded up to 500, according to
1106                          * the MSDN docs, but the MS runtime doesn't
1107                          */
1108                         sock.SendTimeout = 50;
1109                         Assert.AreEqual (50, Approximate (50, sock.SendTimeout), "SendTimeoutChange #1");
1110                         
1111                         sock.SendTimeout = 2000;
1112                         Assert.AreEqual (2000, Approximate (2000, sock.SendTimeout), "SendTimeoutChange #2");
1113                         
1114                         sock.SendTimeout = 0;
1115                         Assert.AreEqual (0, Approximate (0, sock.SendTimeout), "SendTimeoutChange #3");
1116                         
1117                         /* Should be the same as setting 0 */
1118                         sock.SendTimeout = -1;
1119                         Assert.AreEqual (0, sock.SendTimeout, "SendTimeoutChange #4");
1120
1121                         sock.SendTimeout = 65536;
1122                         Assert.AreEqual (65536, Approximate (65536, sock.SendTimeout), "SendTimeoutChange #5");
1123                         
1124                         try {
1125                                 sock.SendTimeout = -2;
1126                                 Assert.Fail ("SendTimeoutChange #8");
1127                         } catch (ArgumentOutOfRangeException) {
1128                         } finally {
1129                                 sock.Close ();
1130                         }
1131                 }
1132
1133                 [Test]
1134                 [ExpectedException (typeof(ObjectDisposedException))]
1135                 public void SendTimeoutClosed ()
1136                 {
1137                         Socket sock = new Socket (AddressFamily.InterNetwork,
1138                                                   SocketType.Stream,
1139                                                   ProtocolType.Tcp);
1140                         
1141                         sock.Close ();
1142                         
1143                         int val = sock.SendTimeout;
1144                 }
1145                 
1146                 [Test]
1147                 public void ReceiveTimeoutDefault ()
1148                 {
1149                         Socket sock = new Socket (AddressFamily.InterNetwork,
1150                                                   SocketType.Stream,
1151                                                   ProtocolType.Tcp);
1152                         
1153                         Assert.AreEqual (0, sock.ReceiveTimeout, "ReceiveTimeoutDefault");
1154                         
1155                         sock.Close ();
1156                 }
1157
1158                 [Test]
1159                 public void ReceiveTimeoutChange ()
1160                 {
1161                         Socket sock = new Socket (AddressFamily.InterNetwork,
1162                                                   SocketType.Stream,
1163                                                   ProtocolType.Tcp);
1164                         
1165                         sock.ReceiveTimeout = 50;
1166                         Assert.AreEqual (50, Approximate (50, sock.ReceiveTimeout), "ReceiveTimeoutChange #1");
1167                         
1168                         sock.ReceiveTimeout = 2000;
1169                         Assert.AreEqual (2000, Approximate (2000, sock.ReceiveTimeout), "ReceiveTimeoutChange #2");
1170                         
1171                         sock.ReceiveTimeout = 0;
1172                         Assert.AreEqual (0, sock.ReceiveTimeout, "ReceiveTimeoutChange #3");
1173                         
1174                         /* Should be the same as setting 0 */
1175                         sock.ReceiveTimeout = -1;
1176                         Assert.AreEqual (0, sock.ReceiveTimeout, "ReceiveTimeoutChange #4");
1177
1178                         sock.ReceiveTimeout = 65536;
1179                         Assert.AreEqual (65536, Approximate (65536, sock.ReceiveTimeout), "ReceiveTimeoutChange #5");
1180                         
1181                         try {
1182                                 sock.ReceiveTimeout = -2;
1183                                 Assert.Fail ("ReceiveTimeoutChange #8");
1184                         } catch (ArgumentOutOfRangeException) {
1185                         } finally {
1186                                 sock.Close ();
1187                         }
1188                 }
1189
1190                 [Test]
1191                 [ExpectedException (typeof(ObjectDisposedException))]
1192                 public void ReceiveTimeoutClosed ()
1193                 {
1194                         Socket sock = new Socket (AddressFamily.InterNetwork,
1195                                                   SocketType.Stream,
1196                                                   ProtocolType.Tcp);
1197                         
1198                         sock.Close ();
1199                         
1200                         int val = sock.ReceiveTimeout;
1201                 }
1202                 
1203                 [Test]
1204                 public void NoDelayDefaultTcp ()
1205                 {
1206                         Socket sock = new Socket (AddressFamily.InterNetwork,
1207                                                   SocketType.Stream,
1208                                                   ProtocolType.Tcp);
1209                         
1210                         Assert.AreEqual (false, sock.NoDelay, "NoDelayDefaultTcp");
1211                         
1212                         sock.Close ();
1213                 }
1214
1215                 [Test]
1216                 public void NoDelayChangeTcp ()
1217                 {
1218                         Socket sock = new Socket (AddressFamily.InterNetwork,
1219                                                   SocketType.Stream,
1220                                                   ProtocolType.Tcp);
1221                         
1222                         sock.NoDelay = true;
1223                         
1224                         Assert.AreEqual (true, sock.NoDelay, "NoDelayChangeTcp");
1225                         
1226                         sock.Close ();
1227                 }
1228                 
1229                 [Test]
1230                 public void NoDelayDefaultUdp ()
1231                 {
1232                         Socket sock = new Socket (AddressFamily.InterNetwork,
1233                                                   SocketType.Dgram,
1234                                                   ProtocolType.Udp);
1235                         
1236                         try {
1237                                 bool val = sock.NoDelay;
1238                                 Assert.Fail ("NoDelayDefaultUdp #1");
1239                         } catch (SocketException ex) {
1240                                 Assert.AreEqual (10042, ex.ErrorCode,
1241                                                  "NoDelayDefaultUdp #2");
1242                         } finally {
1243                                 sock.Close ();
1244                         }
1245                 }
1246
1247                 [Test]
1248                 public void NoDelayChangeUdp ()
1249                 {
1250                         Socket sock = new Socket (AddressFamily.InterNetwork,
1251                                                   SocketType.Dgram,
1252                                                   ProtocolType.Udp);
1253                         
1254                         try {
1255                                 sock.NoDelay = true;
1256                                 Assert.Fail ("NoDelayChangeUdp #1");
1257                         } catch (SocketException ex) {
1258                                 Assert.AreEqual (10042, ex.ErrorCode,
1259                                                  "NoDelayChangeUdp #2");
1260                         } finally {
1261                                 sock.Close ();
1262                         }
1263                 }
1264                 
1265                 [Test]
1266                 [ExpectedException (typeof(ObjectDisposedException))]
1267                 public void NoDelayClosed ()
1268                 {
1269                         Socket sock = new Socket (AddressFamily.InterNetwork,
1270                                                   SocketType.Stream,
1271                                                   ProtocolType.Tcp);
1272                         
1273                         sock.Close ();
1274                         
1275                         bool val = sock.NoDelay;
1276                 }
1277
1278                 static bool BAAccepted = false;
1279                 static Socket BASocket = null;
1280                 static ManualResetEvent BACalledBack = new ManualResetEvent (false);
1281                 
1282                 private static void BACallback (IAsyncResult asyncResult)
1283                 {
1284                         Socket sock = (Socket)asyncResult.AsyncState;
1285                         
1286                         BASocket = sock.EndAccept (asyncResult);
1287                         
1288                         BAAccepted = true;
1289                         BACalledBack.Set ();
1290                 }
1291                 
1292                 [Test]
1293                 [ExpectedException (typeof(InvalidOperationException))]
1294                 public void BeginAcceptNotBound ()
1295                 {
1296                         Socket sock = new Socket (AddressFamily.InterNetwork,
1297                                                   SocketType.Stream,
1298                                                   ProtocolType.Tcp);
1299
1300                         sock.BeginAccept (BACallback, sock);
1301                         
1302                         sock.Close ();
1303                 }
1304                 
1305                 [Test]
1306                 [ExpectedException (typeof(InvalidOperationException))]
1307                 public void BeginAcceptNotListening ()
1308                 {
1309                         Socket sock = new Socket (AddressFamily.InterNetwork,
1310                                                   SocketType.Stream,
1311                                                   ProtocolType.Tcp);
1312
1313                         sock.Bind (new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ()));
1314                         
1315                         sock.BeginAccept (BACallback, sock);
1316                         
1317                         sock.Close ();
1318                 }
1319
1320                 [Test]
1321                 public void BeginAccept ()
1322                 {
1323                         Socket sock = new Socket (AddressFamily.InterNetwork,
1324                                                   SocketType.Stream,
1325                                                   ProtocolType.Tcp);
1326                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
1327                                                         NetworkHelpers.FindFreePort ());
1328                         
1329                         sock.Bind (ep);
1330                         sock.Listen (1);
1331                         
1332                         BACalledBack.Reset ();
1333                         
1334                         sock.BeginAccept (BACallback, sock);
1335
1336                         Socket conn = new Socket (AddressFamily.InterNetwork,
1337                                                   SocketType.Stream,
1338                                                   ProtocolType.Tcp);
1339                         
1340                         conn.Connect (ep);
1341
1342                         if (BACalledBack.WaitOne (2000, false) == false) {
1343                                 Assert.Fail ("BeginAccept wait timed out");
1344                         }
1345                         
1346                         Assert.AreEqual (true, BAAccepted, "BeginAccept #1");
1347                         Assert.AreEqual (true, BASocket.Connected, "BeginAccept #2");
1348                         Assert.AreEqual (false, sock.Connected, "BeginAccept #3");
1349                         Assert.AreEqual (true, conn.Connected, "BeginAccept #4");
1350
1351                         BASocket.Close ();
1352                         conn.Close ();
1353                         sock.Close ();
1354                 }
1355
1356                 [Test]
1357                 [ExpectedException (typeof(ObjectDisposedException))]
1358                 public void BeginAcceptClosed ()
1359                 {
1360                         Socket sock = new Socket (AddressFamily.InterNetwork,
1361                                                   SocketType.Stream,
1362                                                   ProtocolType.Tcp);
1363                         
1364                         sock.Close ();
1365                         
1366                         sock.BeginAccept (BACallback, sock);
1367                 }
1368
1369                 static bool BADAccepted = false;
1370                 static Socket BADSocket = null;
1371                 static byte[] BADBytes;
1372                 static int BADByteCount;
1373                 static ManualResetEvent BADCalledBack = new ManualResetEvent (false);
1374                 
1375                 private static void BADCallback (IAsyncResult asyncResult)
1376                 {
1377                         Socket sock = (Socket)asyncResult.AsyncState;
1378                         
1379                         BADSocket = sock.EndAccept (out BADBytes,
1380                                                     out BADByteCount,
1381                                                     asyncResult);
1382                         
1383                         BADAccepted = true;
1384                         BADCalledBack.Set ();
1385                 }
1386
1387                 [Test]
1388                 public void BeginAcceptData ()
1389                 {
1390                         Socket sock = new Socket (AddressFamily.InterNetwork,
1391                                                   SocketType.Stream,
1392                                                   ProtocolType.Tcp);
1393                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
1394                                                         NetworkHelpers.FindFreePort ());
1395                         
1396                         sock.Bind (ep);
1397                         sock.Listen (1);
1398                         
1399                         BADCalledBack.Reset ();
1400                         
1401                         sock.BeginAccept (256, BADCallback, sock);
1402
1403                         Socket conn = new Socket (AddressFamily.InterNetwork,
1404                                                   SocketType.Stream,
1405                                                   ProtocolType.Tcp);
1406                         byte[] send_bytes = new byte[] {10, 11, 12, 13};
1407                         
1408                         conn.Connect (ep);
1409                         conn.Send (send_bytes);
1410
1411                         if (BADCalledBack.WaitOne (2000, false) == false) {
1412                                 Assert.Fail ("BeginAcceptData wait timed out");
1413                         }
1414                         
1415                         Assert.AreEqual (true, BADAccepted, "BeginAcceptData #1");
1416                         Assert.AreEqual (true, BADSocket.Connected, "BeginAcceptData #2");
1417                         Assert.AreEqual (false, sock.Connected, "BeginAcceptData #3");
1418                         Assert.AreEqual (true, conn.Connected, "BeginAcceptData #4");
1419                         Assert.AreEqual (send_bytes.Length, BADByteCount, "BeginAcceptData #5");
1420                         
1421                         /* The MS runtime gives the returned data in a
1422                          * much bigger array.  TODO: investigate
1423                          * whether it the size correlates to the first
1424                          * parameter in BeginAccept()
1425                          */
1426                         Assert.IsFalse (BADBytes.Length == send_bytes.Length,
1427                                         "BeginAcceptData #6");
1428
1429                         for(int i = 0; i < send_bytes.Length; i++) {
1430                                 Assert.AreEqual (send_bytes[i], BADBytes[i], "BeginAcceptData #" + (i+7).ToString ());
1431                         }
1432
1433                         BADSocket.Close ();
1434                         conn.Close ();
1435                         sock.Close ();
1436                 }
1437
1438                 [Test]
1439                 [ExpectedException (typeof(ObjectDisposedException))]
1440                 public void BeginAcceptDataClosed ()
1441                 {
1442                         Socket sock = new Socket (AddressFamily.InterNetwork,
1443                                                   SocketType.Stream,
1444                                                   ProtocolType.Tcp);
1445                         
1446                         sock.Close ();
1447                         
1448                         sock.BeginAccept (256, BADCallback, sock);
1449                 }
1450
1451                 [Test]
1452                 public void BeginAcceptSocketUdp ()
1453                 {
1454                         Socket sock = new Socket (AddressFamily.InterNetwork,
1455                                                   SocketType.Stream,
1456                                                   ProtocolType.Tcp);
1457                         Socket acc = new Socket (AddressFamily.InterNetwork,
1458                                                  SocketType.Dgram,
1459                                                  ProtocolType.Udp);
1460                         
1461                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
1462                                                         NetworkHelpers.FindFreePort ());
1463                         
1464                         sock.Bind (ep);
1465                         sock.Listen (1);
1466                         
1467                         try {
1468                                 sock.BeginAccept (acc, 256, BADCallback, sock);
1469                                 Assert.Fail ("BeginAcceptSocketUdp #1");
1470                         } catch (SocketException ex) {
1471                                 Assert.AreEqual (10022, ex.ErrorCode, "BeginAcceptSocketUdp #2");
1472                         } finally {
1473                                 acc.Close ();
1474                                 sock.Close ();
1475                         }
1476                 }
1477                 
1478                 [Test]
1479                 public void BeginAcceptSocketBound ()
1480                 {
1481                         Socket sock = new Socket (AddressFamily.InterNetwork,
1482                                                   SocketType.Stream,
1483                                                   ProtocolType.Tcp);
1484                         Socket acc = new Socket (AddressFamily.InterNetwork,
1485                                                  SocketType.Stream,
1486                                                  ProtocolType.Tcp);
1487                         
1488                         IPEndPoint ep1 = new IPEndPoint (IPAddress.Loopback,
1489                                                          NetworkHelpers.FindFreePort ());
1490                         
1491                         IPEndPoint ep2 = new IPEndPoint (IPAddress.Loopback,
1492                                                          NetworkHelpers.FindFreePort ());
1493                         
1494                         sock.Bind (ep1);
1495                         sock.Listen (1);
1496
1497                         acc.Bind (ep2);
1498                         
1499                         try {
1500                                 sock.BeginAccept (acc, 256, BADCallback, sock);
1501                                 Assert.Fail ("BeginAcceptSocketBound #1");
1502                         } catch (InvalidOperationException) {
1503                         } finally {
1504                                 acc.Close ();
1505                                 sock.Close ();
1506                         }
1507                 }
1508                 
1509                 [Test]
1510                 public void BeginAcceptSocket ()
1511                 {
1512                         Socket sock = new Socket (AddressFamily.InterNetwork,
1513                                                   SocketType.Stream,
1514                                                   ProtocolType.Tcp);
1515                         Socket acc = new Socket (AddressFamily.InterNetwork,
1516                                                  SocketType.Stream,
1517                                                  ProtocolType.Tcp);
1518                         
1519                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
1520                                                         NetworkHelpers.FindFreePort ());
1521                         
1522                         sock.Bind (ep);
1523                         sock.Listen (1);
1524                         
1525                         BADCalledBack.Reset ();
1526                         
1527                         sock.BeginAccept (acc, 256, BADCallback, sock);
1528
1529                         Socket conn = new Socket (AddressFamily.InterNetwork,
1530                                                   SocketType.Stream,
1531                                                   ProtocolType.Tcp);
1532                         byte[] send_bytes = new byte[] {10, 11, 12, 13};
1533                         
1534                         conn.Connect (ep);
1535                         conn.Send (send_bytes);
1536
1537                         if (BADCalledBack.WaitOne (2000, false) == false) {
1538                                 Assert.Fail ("BeginAcceptSocket wait timed out");
1539                         }
1540                         
1541                         Assert.AreEqual (true, BADAccepted, "BeginAcceptSocket #1");
1542                         Assert.AreEqual (true, BADSocket.Connected, "BeginAcceptSocket #2");
1543                         Assert.AreEqual (false, sock.Connected, "BeginAcceptSocket #3");
1544                         Assert.AreEqual (true, conn.Connected, "BeginAcceptSocket #4");
1545                         Assert.AreEqual (send_bytes.Length, BADByteCount, "BeginAcceptSocket #5");
1546                         Assert.AreEqual (AddressFamily.InterNetwork, acc.AddressFamily, "BeginAcceptSocket #6");
1547                         Assert.AreEqual (SocketType.Stream, acc.SocketType, "BeginAcceptSocket #7");
1548                         Assert.AreEqual (ProtocolType.Tcp, acc.ProtocolType, "BeginAcceptSocket #8");
1549                         Assert.AreEqual (conn.LocalEndPoint, acc.RemoteEndPoint, "BeginAcceptSocket #9");
1550                         
1551                         /* The MS runtime gives the returned data in a
1552                          * much bigger array.  TODO: investigate
1553                          * whether it the size correlates to the first
1554                          * parameter in BeginAccept()
1555                          */
1556                         Assert.IsFalse (BADBytes.Length == send_bytes.Length,
1557                                         "BeginAcceptSocket #10");
1558
1559                         for(int i = 0; i < send_bytes.Length; i++) {
1560                                 Assert.AreEqual (send_bytes[i], BADBytes[i], "BeginAcceptSocket #" + (i+11).ToString ());
1561                         }
1562
1563                         BADSocket.Close ();
1564                         conn.Close ();
1565                         acc.Close ();
1566                         sock.Close ();
1567                 }
1568
1569                 [Test]
1570                 public void BeginAcceptSocketClosed ()
1571                 {
1572                         Socket sock = new Socket (AddressFamily.InterNetwork,
1573                                                   SocketType.Stream,
1574                                                   ProtocolType.Tcp);
1575                         Socket acc = new Socket (AddressFamily.InterNetwork,
1576                                                  SocketType.Stream,
1577                                                  ProtocolType.Tcp);
1578                         
1579                         sock.Close ();
1580                         
1581                         try {
1582                                 sock.BeginAccept (acc, 256, BADCallback, null);
1583                                 Assert.Fail ("BeginAcceptSocketClosed #1");
1584                         } catch (ObjectDisposedException) {
1585                         } finally {
1586                                 acc.Close ();
1587                         }
1588                 }
1589
1590                 [Test]
1591                 public void BeginAcceptSocketAccClosed ()
1592                 {
1593                         Socket sock = new Socket (AddressFamily.InterNetwork,
1594                                                   SocketType.Stream,
1595                                                   ProtocolType.Tcp);
1596                         Socket acc = new Socket (AddressFamily.InterNetwork,
1597                                                  SocketType.Stream,
1598                                                  ProtocolType.Tcp);
1599                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
1600                                                         NetworkHelpers.FindFreePort ());
1601
1602                         sock.Bind (ep);
1603                         sock.Listen (1);
1604                         
1605                         acc.Close ();
1606                         
1607                         BADCalledBack.Reset ();
1608                         
1609                         try {
1610                                 sock.BeginAccept (acc, 256, BADCallback, null);
1611                                 Assert.Fail ("BeginAcceptSocketAccClosed #1");
1612                         } catch (ObjectDisposedException) {
1613                         } finally {
1614                                 sock.Close ();
1615                         }
1616                 }
1617                 
1618                 static bool BCConnected = false;
1619                 static ManualResetEvent BCCalledBack = new ManualResetEvent (false);
1620                 
1621                 private static void BCCallback (IAsyncResult asyncResult)
1622                 {
1623                         Socket sock = (Socket)asyncResult.AsyncState;
1624                         
1625                         try {
1626                                 sock.EndConnect (asyncResult);
1627                         } catch (Exception e) {
1628                                 Console.WriteLine ("BCCallback exception:");
1629                                 Console.WriteLine (e);
1630
1631                                 throw;
1632                         }
1633
1634                         BCConnected = true;
1635                         
1636                         BCCalledBack.Set ();
1637                 }
1638                 
1639                 [Test]
1640                 public void BeginConnectAddressPort ()
1641                 {
1642                         Socket sock = new Socket (AddressFamily.InterNetwork,
1643                                                   SocketType.Stream,
1644                                                   ProtocolType.Tcp);
1645                         Socket listen = new Socket (AddressFamily.InterNetwork,
1646                                                     SocketType.Stream,
1647                                                     ProtocolType.Tcp);
1648                         IPAddress ip = IPAddress.Loopback;
1649                         IPEndPoint ep = new IPEndPoint (ip, NetworkHelpers.FindFreePort ());
1650
1651                         listen.Bind (ep);
1652                         listen.Listen (1);
1653                         
1654                         BCCalledBack.Reset ();
1655                         
1656                         BCConnected = false;
1657                         
1658                         sock.BeginConnect (ip, ep.Port, BCCallback, sock);
1659
1660                         if (BCCalledBack.WaitOne (2000, false) == false) {
1661                                 Assert.Fail ("BeginConnectAddressPort wait timed out");
1662                         }
1663                         
1664                         Assert.AreEqual (true, BCConnected, "BeginConnectAddressPort #1");
1665                         
1666                         sock.Close ();
1667                         listen.Close ();
1668                 }
1669
1670                 [Test]
1671                 public void BeginConnectAddressPortNull ()
1672                 {
1673                         Socket sock = new Socket (AddressFamily.InterNetwork,
1674                                                   SocketType.Stream,
1675                                                   ProtocolType.Tcp);
1676                         IPAddress ip = null;
1677
1678                         try {
1679                                 sock.BeginConnect (ip, 1244, BCCallback,
1680                                                    sock);
1681                                 Assert.Fail ("BeginConnectAddressPortNull #1");
1682                         } catch (ArgumentNullException) {
1683                         } finally {
1684                                 sock.Close ();
1685                         }
1686                 }
1687
1688                 [Test]
1689                 public void BeginConnectAddressPortListen ()
1690                 {
1691                         Socket sock = new Socket (AddressFamily.InterNetwork,
1692                                                   SocketType.Stream,
1693                                                   ProtocolType.Tcp);
1694                         IPAddress ip = IPAddress.Loopback;
1695                         IPEndPoint ep = new IPEndPoint (ip, NetworkHelpers.FindFreePort ());
1696
1697                         sock.Bind (ep);
1698                         sock.Listen (1);
1699                         
1700                         try {
1701                                 sock.BeginConnect (ip, ep.Port, BCCallback, sock);
1702                                 Assert.Fail ("BeginConnectAddressPortListen #1");
1703                         } catch (InvalidOperationException) {
1704                         } finally {
1705                                 sock.Close ();
1706                         }
1707                 }
1708                 
1709                 [Test]
1710                 [ExpectedException (typeof(ObjectDisposedException))]
1711                 public void BeginConnectAddressPortClosed ()
1712                 {
1713                         Socket sock = new Socket (AddressFamily.InterNetwork,
1714                                                   SocketType.Stream,
1715                                                   ProtocolType.Tcp);
1716                         IPAddress ip = IPAddress.Loopback;
1717                         
1718                         sock.Close ();
1719                         
1720                         sock.BeginConnect (ip, 1244, BCCallback, sock);
1721                 }
1722                 
1723                 [Test]
1724                 [Category ("NotOnMac")]
1725                 /*
1726                  * This is not a Mono bug.
1727                  * 
1728                  * By default, only 127.0.0.1 is enabled and you must explicitly
1729                  * enable additional addresses using 'sudo ifconfig lo0 alias 127.0.0.1'.
1730                  * 
1731                  * I tested this on Mac OS 10.7.4; a 'ping 127.0.0.2' does not work
1732                  * until I add that alias.
1733                  * 
1734                  */
1735                 public void BeginConnectMultiple ()
1736                 {
1737                         Socket sock = new Socket (AddressFamily.InterNetwork,
1738                                                   SocketType.Stream,
1739                                                   ProtocolType.Tcp);
1740                         Socket listen = new Socket (AddressFamily.InterNetwork,
1741                                                     SocketType.Stream,
1742                                                     ProtocolType.Tcp);
1743                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
1744                                                         NetworkHelpers.FindFreePort ());
1745                         IPAddress[] ips = new IPAddress[4];
1746                         
1747                         ips[0] = IPAddress.Parse ("127.0.0.4");
1748                         ips[1] = IPAddress.Parse ("127.0.0.3");
1749                         ips[2] = IPAddress.Parse ("127.0.0.2");
1750                         ips[3] = IPAddress.Parse ("127.0.0.1");
1751
1752                         listen.Bind (ep);
1753                         listen.Listen (1);
1754                         
1755                         BCCalledBack.Reset ();
1756                         
1757                         BCConnected = false;
1758                         
1759                         sock.BeginConnect (ips, ep.Port, BCCallback, sock);
1760                         
1761                         /* Longer wait here, because the ms runtime
1762                          * takes a lot longer to not connect
1763                          */
1764                         /*
1765                         if (BCCalledBack.WaitOne (30000, false) == false) {
1766                                 Assert.Fail ("BeginConnectMultiple wait failed");
1767                         }
1768                         */
1769
1770                         Assert.IsTrue (BCCalledBack.WaitOne (30000), "#0");
1771                         
1772                         Assert.AreEqual (true, BCConnected, "BeginConnectMultiple #1");
1773                         Assert.AreEqual (AddressFamily.InterNetwork, sock.RemoteEndPoint.AddressFamily, "BeginConnectMultiple #2");
1774                         IPEndPoint remep = (IPEndPoint)sock.RemoteEndPoint;
1775                         
1776                         Assert.AreEqual (IPAddress.Loopback, remep.Address, "BeginConnectMultiple #2");
1777                         
1778                         sock.Close ();
1779                         listen.Close ();
1780                 }
1781
1782                 [Test]
1783                 public void BeginConnectMultiple2 ()
1784                 {
1785                         Socket sock = new Socket (AddressFamily.InterNetwork,
1786                                                   SocketType.Stream,
1787                                                   ProtocolType.Tcp);
1788                         Socket listen = new Socket (AddressFamily.InterNetwork,
1789                                                     SocketType.Stream,
1790                                                     ProtocolType.Tcp);
1791
1792                         // Need at least two addresses.
1793                         var ips = Dns.GetHostAddresses (string.Empty);
1794                         if (ips.Length < 1)
1795                                 Assert.Ignore ("This test needs at least two IP addresses.");
1796
1797                         var allIps = new IPAddress [ips.Length + 1];
1798                         allIps [0] = IPAddress.Loopback;
1799                         ips.CopyTo (allIps, 1);
1800
1801                         /*
1802                          * Only bind to the loopback interface, so all the non-loopback
1803                          * IP addresses will fail.  BeginConnect()/EndConnect() should
1804                          * succeed it it can connect to at least one of the requested
1805                          * addresses.
1806                          */
1807                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
1808
1809                         listen.Bind (ep);
1810                         listen.Listen (1);
1811                         
1812                         BCCalledBack.Reset ();
1813                         
1814                         BCConnected = false;
1815                         
1816                         sock.BeginConnect (allIps, ep.Port, BCCallback, sock);
1817                         
1818                         /* Longer wait here, because the ms runtime
1819                          * takes a lot longer to not connect
1820                          */
1821                         if (BCCalledBack.WaitOne (10000, false) == false) {
1822                                 Assert.Fail ("BeginConnectMultiple2 wait failed");
1823                         }
1824                         
1825                         Assert.AreEqual (true, BCConnected, "BeginConnectMultiple2 #1");
1826                         Assert.AreEqual (AddressFamily.InterNetwork, sock.RemoteEndPoint.AddressFamily, "BeginConnectMultiple2 #2");
1827                         IPEndPoint remep = (IPEndPoint)sock.RemoteEndPoint;
1828
1829                         Assert.AreEqual (IPAddress.Loopback, remep.Address, "BeginConnectMultiple2 #2");
1830
1831                         sock.Close ();
1832                         listen.Close ();
1833                 }
1834
1835
1836                 [Test]
1837                 public void BeginConnectMultipleNull ()
1838                 {
1839                         Socket sock = new Socket (AddressFamily.InterNetwork,
1840                                                   SocketType.Stream,
1841                                                   ProtocolType.Tcp);
1842                         IPAddress[] ips = null;
1843                         
1844                         try {
1845                                 sock.BeginConnect (ips, 1246, BCCallback,
1846                                                    sock);
1847                                 Assert.Fail ("BeginConnectMultipleNull #1");
1848                         } catch (ArgumentNullException) {
1849                         } finally {
1850                                 sock.Close ();
1851                         }
1852                 }
1853
1854                 [Test]
1855                 public void BeginConnectMultipleListen ()
1856                 {
1857                         Socket sock = new Socket (AddressFamily.InterNetwork,
1858                                                   SocketType.Stream,
1859                                                   ProtocolType.Tcp);
1860                         IPAddress[] ips = new IPAddress[4];
1861                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
1862                                                         NetworkHelpers.FindFreePort ());
1863                         
1864                         ips[0] = IPAddress.Parse ("127.0.0.4");
1865                         ips[1] = IPAddress.Parse ("127.0.0.3");
1866                         ips[2] = IPAddress.Parse ("127.0.0.2");
1867                         ips[3] = IPAddress.Parse ("127.0.0.1");
1868                         
1869                         sock.Bind (ep);
1870                         sock.Listen (1);
1871                         
1872                         try {
1873                                 sock.BeginConnect (ips, ep.Port, BCCallback,
1874                                                    sock);
1875                                 Assert.Fail ("BeginConnectMultipleListen #1");
1876                         } catch (InvalidOperationException) {
1877                         } finally {
1878                                 sock.Close ();
1879                         }
1880                 }
1881                 
1882                 [Test]
1883                 [ExpectedException (typeof(ObjectDisposedException))]
1884                 public void BeginConnectMultipleClosed ()
1885                 {
1886                         Socket sock = new Socket (AddressFamily.InterNetwork,
1887                                                   SocketType.Stream,
1888                                                   ProtocolType.Tcp);
1889                         IPAddress[] ips = new IPAddress[4];
1890                         
1891                         ips[0] = IPAddress.Parse ("127.0.0.4");
1892                         ips[1] = IPAddress.Parse ("127.0.0.3");
1893                         ips[2] = IPAddress.Parse ("127.0.0.2");
1894                         ips[3] = IPAddress.Parse ("127.0.0.1");
1895                         
1896                         sock.Close ();
1897                         
1898                         sock.BeginConnect (ips, 1247, BCCallback, sock);
1899                 }
1900                 
1901                 [Test]
1902                 public void BeginConnectHostPortNull ()
1903                 {
1904                         Socket sock = new Socket (AddressFamily.InterNetwork,
1905                                                   SocketType.Stream,
1906                                                   ProtocolType.Tcp);
1907                         
1908                         try {
1909                                 sock.BeginConnect ((string)null, 0,
1910                                                    BCCallback, sock);
1911                                 Assert.Fail ("BeginConnectHostPort #1");
1912                         } catch (ArgumentNullException) {
1913                         } finally {
1914                                 sock.Close ();
1915                         }
1916                 }
1917
1918                 [Test]
1919                 public void BeginConnectHostPortListen ()
1920                 {
1921                         Socket sock = new Socket (AddressFamily.InterNetwork,
1922                                                   SocketType.Stream,
1923                                                   ProtocolType.Tcp);
1924                         IPAddress ip = IPAddress.Loopback;
1925                         IPEndPoint ep = new IPEndPoint (ip, NetworkHelpers.FindFreePort ());
1926                         
1927                         sock.Bind (ep);
1928                         sock.Listen (1);
1929                         
1930                         try {
1931                                 sock.BeginConnect ("localhost", ep.Port,
1932                                                    BCCallback, sock);
1933                                 Assert.Fail ("BeginConnectHostPortListen #1");
1934                         } catch (InvalidOperationException) {
1935                         } finally {
1936                                 sock.Close ();
1937                         }
1938                 }
1939
1940                 [Test]
1941                 [Category ("NotWorking")] // Need to pick a non-IP AddressFamily that "works" on both mono and ms, this one only works on ms
1942                 public void BeginConnectHostPortNotIP ()
1943                 {
1944                         Socket sock = new Socket (AddressFamily.NetBios,
1945                                                   SocketType.Seqpacket,
1946                                                   ProtocolType.Unspecified);
1947                         
1948                         try {
1949                                 sock.BeginConnect ("localhost", 0, BCCallback,
1950                                                    sock);
1951                                 Assert.Fail ("BeginConnectHostPortNotIP #1");
1952                         } catch (NotSupportedException) {
1953                         } finally {
1954                                 sock.Close ();
1955                         }
1956                 }
1957
1958                 [Test]
1959                 [ExpectedException (typeof(ObjectDisposedException))]
1960                 public void BeginConnectHostPortClosed ()
1961                 {
1962                         Socket sock = new Socket (AddressFamily.InterNetwork,
1963                                                   SocketType.Stream,
1964                                                   ProtocolType.Tcp);
1965                         
1966                         sock.Close ();
1967                         
1968                         sock.BeginConnect ("localhost", 0, BCCallback, sock);
1969                 }
1970                 
1971                 static bool BDDisconnected = false;
1972                 static ManualResetEvent BDCalledBack = new ManualResetEvent (false);
1973                 
1974                 private static void BDCallback (IAsyncResult asyncResult)
1975                 {
1976                         Socket sock = (Socket)asyncResult.AsyncState;
1977                         
1978                         sock.EndDisconnect (asyncResult);
1979                         BDDisconnected = true;
1980                         
1981                         BDCalledBack.Set ();
1982                 }
1983                 
1984                 [Test]
1985                 [Category ("NotDotNet")] // "Needs XP or later"
1986                 public void BeginDisconnect ()
1987                 {
1988                         Socket sock = new Socket (AddressFamily.InterNetwork,
1989                                                   SocketType.Stream,
1990                                                   ProtocolType.Tcp);
1991                         Socket listen = new Socket (AddressFamily.InterNetwork,
1992                                                     SocketType.Stream,
1993                                                     ProtocolType.Tcp);
1994                         IPAddress ip = IPAddress.Loopback;
1995                         IPEndPoint ep = new IPEndPoint (ip, NetworkHelpers.FindFreePort ());
1996                         
1997                         listen.Bind (ep);
1998                         listen.Listen (1);
1999                         
2000                         sock.Connect (ip, ep.Port);
2001                         
2002                         Assert.AreEqual (true, sock.Connected, "BeginDisconnect #1");
2003                         
2004                         sock.Shutdown (SocketShutdown.Both);
2005
2006                         BDCalledBack.Reset ();
2007                         BDDisconnected = false;
2008                         
2009                         sock.BeginDisconnect (false, BDCallback, sock);
2010                 
2011                         if (BDCalledBack.WaitOne (2000, false) == false) {
2012                                 Assert.Fail ("BeginDisconnect wait timed out");
2013                         }
2014                         
2015                         Assert.AreEqual (true, BDDisconnected, "BeginDisconnect #2");
2016                         Assert.AreEqual (false, sock.Connected, "BeginDisconnect #3");
2017                         
2018                         sock.Close ();
2019                         listen.Close ();
2020                 }
2021                 
2022                 [Test]
2023                 public void BeginReceiveSocketError ()
2024                 {
2025                 }
2026                 
2027                 [Test]
2028                 public void BeginReceiveGeneric ()
2029                 {
2030                 }
2031                 
2032                 [Test]
2033                 public void BeginReceiveGenericSocketError ()
2034                 {
2035                 }
2036                 
2037                 private static void BSCallback (IAsyncResult asyncResult)
2038                 {
2039                         Socket sock = (Socket)asyncResult.AsyncState;
2040                         
2041                         sock.EndSend (asyncResult);
2042                 }
2043                 
2044                 [Test]
2045                 public void BeginSendNotConnected ()
2046                 {
2047                         Socket sock = new Socket (AddressFamily.InterNetwork,
2048                                                   SocketType.Stream,
2049                                                   ProtocolType.Tcp);
2050                         
2051                         byte[] send_bytes = new byte[] {10, 11, 12, 13};
2052                         
2053                         try {
2054                                 sock.BeginSend (send_bytes, 0,
2055                                                 send_bytes.Length,
2056                                                 SocketFlags.None, BSCallback,
2057                                                 sock);
2058                                 Assert.Fail ("BeginSendNotConnected #1");
2059                         } catch (SocketException ex) {
2060                                 Assert.AreEqual (10057, ex.ErrorCode, "BeginSendNotConnected #2");
2061                         } finally {
2062                                 sock.Close ();
2063                         }
2064                 }
2065                 
2066                 [Test]
2067                 public void BeginSendSocketError ()
2068                 {
2069                 }
2070                 
2071                 [Test]
2072                 public void BeginSendGeneric ()
2073                 {
2074                 }
2075                 
2076                 [Test]
2077                 public void BeginSendGenericSocketError ()
2078                 {
2079                 }
2080                 
2081                 [Test]
2082                 public void BindTwice ()
2083                 {
2084                         Socket sock = new Socket (AddressFamily.InterNetwork,
2085                                                   SocketType.Stream,
2086                                                   ProtocolType.Tcp);
2087                         IPEndPoint ep1 = new IPEndPoint (IPAddress.Loopback,
2088                                                         NetworkHelpers.FindFreePort ());
2089                         IPEndPoint ep2 = new IPEndPoint (IPAddress.Loopback,
2090                                                          NetworkHelpers.FindFreePort ());
2091                         
2092                         sock.Bind (ep1);
2093                         
2094                         try {
2095                                 sock.Bind (ep2);
2096                                 Assert.Fail ("BindTwice #1");
2097                         } catch (SocketException ex) {
2098                                 Assert.AreEqual (10022, ex.ErrorCode, "BindTwice #2");
2099                         } finally {
2100                                 sock.Close ();
2101                         }
2102                 }
2103                 
2104                 [Test]
2105                 public void Close ()
2106                 {
2107                         Socket sock = new Socket (AddressFamily.InterNetwork,
2108                                                   SocketType.Stream,
2109                                                   ProtocolType.Tcp);
2110                         Socket listen = new Socket (AddressFamily.InterNetwork,
2111                                                     SocketType.Stream,
2112                                                     ProtocolType.Tcp);
2113                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
2114                                                         NetworkHelpers.FindFreePort ());
2115                         
2116                         listen.Bind (ep);
2117                         listen.Listen (1);
2118                         
2119                         sock.Connect (ep);
2120
2121                         Assert.AreEqual (true, sock.Connected, "Close #1");
2122                         
2123                         sock.Close (2);
2124                         
2125                         Thread.Sleep (3000);
2126                         
2127                         Assert.AreEqual (false, sock.Connected, "Close #2");
2128                         
2129                         listen.Close ();
2130                 }
2131                 
2132                 [Test]
2133                 public void ConnectAddressPort ()
2134                 {
2135                         Socket sock = new Socket (AddressFamily.InterNetwork,
2136                                                   SocketType.Stream,
2137                                                   ProtocolType.Tcp);
2138                         Socket listen = new Socket (AddressFamily.InterNetwork,
2139                                                     SocketType.Stream,
2140                                                     ProtocolType.Tcp);
2141                         IPAddress ip = IPAddress.Loopback;
2142                         IPEndPoint ep = new IPEndPoint (ip, NetworkHelpers.FindFreePort ());
2143
2144                         listen.Bind (ep);
2145                         listen.Listen (1);
2146                         
2147                         sock.Connect (ip, ep.Port);
2148                         
2149                         Assert.AreEqual (true, sock.Connected, "ConnectAddressPort #1");
2150                         
2151                         sock.Close ();
2152                         listen.Close ();
2153                 }
2154
2155                 [Test]
2156                 public void ConnectAddressPortNull ()
2157                 {
2158                         Socket sock = new Socket (AddressFamily.InterNetwork,
2159                                                   SocketType.Stream,
2160                                                   ProtocolType.Tcp);
2161                         IPAddress ip = null;
2162
2163                         try {
2164                                 sock.Connect (ip, 1249);
2165                                 Assert.Fail ("ConnectAddressPortNull #1");
2166                         } catch (ArgumentNullException) {
2167                         } finally {
2168                                 sock.Close ();
2169                         }
2170                 }
2171
2172                 [Test]
2173                 public void ConnectAddressPortListen ()
2174                 {
2175                         Socket sock = new Socket (AddressFamily.InterNetwork,
2176                                                   SocketType.Stream,
2177                                                   ProtocolType.Tcp);
2178                         IPAddress ip = IPAddress.Loopback;
2179                         IPEndPoint ep = new IPEndPoint (ip, NetworkHelpers.FindFreePort ());
2180
2181                         sock.Bind (ep);
2182                         sock.Listen (1);
2183                         
2184                         try {
2185                                 sock.Connect (ip, ep.Port);
2186                                 Assert.Fail ("ConnectAddressPortListen #1");
2187                         } catch (InvalidOperationException) {
2188                         } finally {
2189                                 sock.Close ();
2190                         }
2191                 }
2192                 
2193                 [Test]
2194                 [ExpectedException (typeof(ObjectDisposedException))]
2195                 public void ConnectAddressPortClosed ()
2196                 {
2197                         Socket sock = new Socket (AddressFamily.InterNetwork,
2198                                                   SocketType.Stream,
2199                                                   ProtocolType.Tcp);
2200                         IPAddress ip = IPAddress.Loopback;
2201                         
2202                         sock.Close ();
2203                         
2204                         sock.Connect (ip, 1250);
2205                 }
2206                 
2207                 [Test]
2208                 [Category ("NotOnMac")] // MacOSX trashes the fd after the failed connect attempt to 127.0.0.4
2209                 /*
2210                  * This is not a Mono bug.
2211                  * 
2212                  * By default, only 127.0.0.1 is enabled and you must explicitly
2213                  * enable additional addresses using 'sudo ifconfig lo0 alias 127.0.0.1'.
2214                  * 
2215                  * I tested this on Mac OS 10.7.4; a 'ping 127.0.0.2' does not work
2216                  * until I add that alias.
2217                  * 
2218                  * However, after doing so, Mac OS treats these as separate addresses, ie. attempting
2219                  * to connect to 127.0.0.4 yields a connection refused.
2220                  * 
2221                  * When using Connect(), the .NET runtime also throws an exception if connecting to
2222                  * any of the IP addresses fails.  This is different with BeginConnect()/EndConnect()
2223                  * which succeeds when it can connect to at least one of the addresses.
2224                  * 
2225                  */
2226                 public void ConnectMultiple ()
2227                 {
2228                         Socket sock = new Socket (AddressFamily.InterNetwork,
2229                                                   SocketType.Stream,
2230                                                   ProtocolType.Tcp);
2231                         Socket listen = new Socket (AddressFamily.InterNetwork,
2232                                                     SocketType.Stream,
2233                                                     ProtocolType.Tcp);
2234                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
2235                                                         NetworkHelpers.FindFreePort ());
2236                         IPAddress[] ips = new IPAddress[4];
2237                         
2238                         ips[0] = IPAddress.Parse ("127.0.0.4");
2239                         ips[1] = IPAddress.Parse ("127.0.0.3");
2240                         ips[2] = IPAddress.Parse ("127.0.0.2");
2241                         ips[3] = IPAddress.Parse ("127.0.0.1");
2242
2243                         listen.Bind (ep);
2244                         listen.Listen (1);
2245                         
2246                         sock.Connect (ips, ep.Port);
2247                         
2248                         Assert.AreEqual (true, sock.Connected, "ConnectMultiple #1");
2249                         Assert.AreEqual (AddressFamily.InterNetwork, sock.RemoteEndPoint.AddressFamily, "ConnectMultiple #2");
2250                         IPEndPoint remep = (IPEndPoint)sock.RemoteEndPoint;
2251                         
2252                         Assert.AreEqual (IPAddress.Loopback, remep.Address, "ConnectMultiple #2");
2253                         
2254                         sock.Close ();
2255                         listen.Close ();
2256                 }
2257
2258                 [Test]
2259                 public void ConnectMultiple2 ()
2260                 {
2261                         Socket sock = new Socket (AddressFamily.InterNetwork,
2262                                                   SocketType.Stream,
2263                                                   ProtocolType.Tcp);
2264                         Socket listen = new Socket (AddressFamily.InterNetwork,
2265                                                     SocketType.Stream,
2266                                                     ProtocolType.Tcp);
2267
2268                         // Need at least two addresses.
2269                         var ips = Dns.GetHostAddresses (string.Empty);
2270                         if (ips.Length < 1)
2271                                 Assert.Ignore ("This test needs at least two IP addresses.");
2272
2273                         var allIps = new IPAddress [ips.Length + 1];
2274                         allIps [0] = IPAddress.Loopback;
2275                         ips.CopyTo (allIps, 1);
2276
2277                         /*
2278                          * Bind to IPAddress.Any; Connect() will fail unless it can
2279                          * connect to all the addresses in allIps.
2280                          */
2281                         IPEndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
2282
2283                         listen.Bind (ep);
2284                         listen.Listen (1);
2285                         
2286                         sock.Connect (allIps, ep.Port);
2287                         
2288                         Assert.AreEqual (true, sock.Connected, "ConnectMultiple2 #1");
2289                         Assert.AreEqual (AddressFamily.InterNetwork, sock.RemoteEndPoint.AddressFamily, "ConnectMultiple2 #2");
2290                         IPEndPoint remep = (IPEndPoint)sock.RemoteEndPoint;
2291
2292                         Assert.AreEqual (IPAddress.Loopback, remep.Address, "ConnectMultiple2 #3");
2293                         
2294                         sock.Close ();
2295                         listen.Close ();
2296                 }
2297
2298                 [Test]
2299                 public void ConnectMultipleNull ()
2300                 {
2301                         Socket sock = new Socket (AddressFamily.InterNetwork,
2302                                                   SocketType.Stream,
2303                                                   ProtocolType.Tcp);
2304                         IPAddress[] ips = null;
2305                         
2306                         try {
2307                                 sock.Connect (ips, 1251);
2308                                 Assert.Fail ("ConnectMultipleNull #1");
2309                         } catch (ArgumentNullException) {
2310                         } finally {
2311                                 sock.Close ();
2312                         }
2313                 }
2314
2315                 [Test]
2316                 public void ConnectMultipleListen ()
2317                 {
2318                         Socket sock = new Socket (AddressFamily.InterNetwork,
2319                                                   SocketType.Stream,
2320                                                   ProtocolType.Tcp);
2321                         IPAddress[] ips = new IPAddress[4];
2322                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
2323                                                         NetworkHelpers.FindFreePort ());
2324                         
2325                         ips[0] = IPAddress.Parse ("127.0.0.4");
2326                         ips[1] = IPAddress.Parse ("127.0.0.3");
2327                         ips[2] = IPAddress.Parse ("127.0.0.2");
2328                         ips[3] = IPAddress.Parse ("127.0.0.1");
2329                         
2330                         sock.Bind (ep);
2331                         sock.Listen (1);
2332                         
2333                         try {
2334                                 sock.Connect (ips, ep.Port);
2335                                 Assert.Fail ("ConnectMultipleListen #1");
2336                         } catch (InvalidOperationException) {
2337                         } finally {
2338                                 sock.Close ();
2339                         }
2340                 }
2341                 
2342                 [Test]
2343                 [ExpectedException (typeof(ObjectDisposedException))]
2344                 public void ConnectMultipleClosed ()
2345                 {
2346                         Socket sock = new Socket (AddressFamily.InterNetwork,
2347                                                   SocketType.Stream,
2348                                                   ProtocolType.Tcp);
2349                         IPAddress[] ips = new IPAddress[4];
2350                         
2351                         ips[0] = IPAddress.Parse ("127.0.0.4");
2352                         ips[1] = IPAddress.Parse ("127.0.0.3");
2353                         ips[2] = IPAddress.Parse ("127.0.0.2");
2354                         ips[3] = IPAddress.Parse ("127.0.0.1");
2355                         
2356                         sock.Close ();
2357                         
2358                         sock.Connect (ips, 1252);
2359                 }
2360                 
2361                 [Test]
2362                 public void ConnectHostPortNull ()
2363                 {
2364                         Socket sock = new Socket (AddressFamily.InterNetwork,
2365                                                   SocketType.Stream,
2366                                                   ProtocolType.Tcp);
2367                         
2368                         try {
2369                                 sock.Connect ((string)null, 0);
2370                                 Assert.Fail ("ConnectHostPort #1");
2371                         } catch (ArgumentNullException) {
2372                         } finally {
2373                                 sock.Close ();
2374                         }
2375                 }
2376
2377                 [Test]
2378                 public void ConnectHostPortListen ()
2379                 {
2380                         Socket sock = new Socket (AddressFamily.InterNetwork,
2381                                                   SocketType.Stream,
2382                                                   ProtocolType.Tcp);
2383                         IPAddress ip = IPAddress.Loopback;
2384                         IPEndPoint ep = new IPEndPoint (ip, NetworkHelpers.FindFreePort ());
2385                         
2386                         sock.Bind (ep);
2387                         sock.Listen (1);
2388                         
2389                         try {
2390                                 sock.Connect ("localhost", ep.Port);
2391                                 Assert.Fail ("ConnectHostPortListen #1");
2392                         } catch (InvalidOperationException) {
2393                         } finally {
2394                                 sock.Close ();
2395                         }
2396                 }
2397
2398                 [Test]
2399                 [Category ("NotWorking")] // Need to pick a non-IP AddressFamily that "works" on both mono and ms, this one only works on ms
2400                 public void ConnectHostPortNotIP ()
2401                 {
2402                         Socket sock = new Socket (AddressFamily.NetBios,
2403                                                   SocketType.Seqpacket,
2404                                                   ProtocolType.Unspecified);
2405                         
2406                         try {
2407                                 sock.Connect ("localhost", 0);
2408                                 Assert.Fail ("ConnectHostPortNotIP #1");
2409                         } catch (NotSupportedException) {
2410                         } finally {
2411                                 sock.Close ();
2412                         }
2413                 }
2414
2415                 [Test]
2416                 [ExpectedException (typeof(ObjectDisposedException))]
2417                 public void ConnectHostPortClosed ()
2418                 {
2419                         Socket sock = new Socket (AddressFamily.InterNetwork,
2420                                                   SocketType.Stream,
2421                                                   ProtocolType.Tcp);
2422                         
2423                         sock.Close ();
2424                         
2425                         sock.Connect ("localhost", 0);
2426                 }
2427                 
2428                 [Test]
2429                 [Category ("NotDotNet")] // "Needs XP or later"
2430                 public void Disconnect ()
2431                 {
2432                         Socket sock = new Socket (AddressFamily.InterNetwork,
2433                                                   SocketType.Stream,
2434                                                   ProtocolType.Tcp);
2435                         Socket listen = new Socket (AddressFamily.InterNetwork,
2436                                                     SocketType.Stream,
2437                                                     ProtocolType.Tcp);
2438                         IPAddress ip = IPAddress.Loopback;
2439                         IPEndPoint ep = new IPEndPoint (ip, NetworkHelpers.FindFreePort ());
2440                         
2441                         listen.Bind (ep);
2442                         listen.Listen (1);
2443                         
2444                         sock.Connect (ip, ep.Port);
2445                         
2446                         Assert.AreEqual (true, sock.Connected, "Disconnect #1");
2447                         
2448                         sock.Shutdown (SocketShutdown.Both);
2449
2450                         sock.Disconnect (false);
2451
2452                         Assert.AreEqual (false, sock.Connected, "BeginDisconnect #3");
2453                         
2454                         sock.Close ();
2455                         listen.Close ();
2456                 }
2457                 
2458                 [Test]
2459                 public void DuplicateAndClose ()
2460                 {
2461                 }
2462                 
2463                 [Test]
2464                 public void IOControl ()
2465                 {
2466                 }
2467
2468                 [Test]
2469                 public void TestDefaultsDualMode ()
2470                 {
2471                         using (var socket = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)){
2472                                 Assert.IsTrue (socket.DualMode, "In Mono, DualMode must be true when constructing InterNetworkV6 sockets");
2473                         }
2474
2475                         using (var socket = new Socket (SocketType.Stream, ProtocolType.Tcp)){
2476                                 Assert.AreEqual (AddressFamily.InterNetworkV6, socket.AddressFamily, "When creating sockets of type stream/tcp, the address family should be InterNetworkV6");
2477                                 Assert.IsTrue (socket.DualMode, "In Mono, DualMode must be true when constructing InterNetworkV6 sockets");
2478
2479                                 socket.DualMode = false;
2480
2481                                 Assert.IsFalse (socket.DualMode, "Setting of DualSocket should turn DualSockets off");
2482                         }
2483                         
2484                 }
2485                 
2486                 [Test]
2487                 public void ReceiveGeneric ()
2488                 {
2489                         int i;
2490
2491                         IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, NetworkHelpers.FindFreePort ());
2492
2493                         Socket listensock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
2494                         listensock.Bind (endpoint);
2495                         listensock.Listen(1);
2496
2497                         Socket sendsock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
2498                         sendsock.Connect(endpoint);
2499
2500                         Socket clientsock = listensock.Accept();
2501                         
2502                         byte[] sendbuf = new byte[256];
2503
2504                         for(i = 0; i < 256; i++) {
2505                                 sendbuf[i] = (byte)i;
2506                         }
2507                         for (i = 4; i < 6; i++) {
2508                                 Assert.AreEqual (sendbuf[i], (byte)i,
2509                                                  "#1/" + i.ToString());
2510                         }
2511
2512                         SocketError err;
2513                         sendsock.Send (sendbuf, 0, 256, SocketFlags.None,
2514                                        out err);
2515
2516
2517                         byte[] recvbuf = new byte[256];
2518                         List<ArraySegment<byte>> recvbuflist = new List<ArraySegment<byte>>(2);
2519                         recvbuflist.Add(new ArraySegment<byte>(recvbuf, 4, 2));
2520                         recvbuflist.Add(new ArraySegment<byte>(recvbuf, 20, 230));
2521                         
2522                         clientsock.Receive (recvbuflist);
2523
2524                         /* recvbuf should now hold the first 2 bytes
2525                          * of sendbuf from pos 4, and the next 230
2526                          * bytes of sendbuf from pos 20
2527                          */
2528
2529                         for (i = 0; i < 2; i++) {
2530                                 Assert.AreEqual (sendbuf[i], recvbuf[i + 4],
2531                                                  "#2/" + i.ToString());
2532                         }
2533                         for (i = 2; i < 232; i++) {
2534                                 Assert.AreEqual (sendbuf[i], recvbuf[i + 18],
2535                                                  "#2/" + i.ToString());
2536                         }
2537
2538                         sendsock.Close ();
2539                         clientsock.Close ();
2540                         listensock.Close ();
2541                 }
2542                 
2543                 [Test]
2544                 public void SendGeneric ()
2545                 {
2546                         int i;
2547
2548                         IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, NetworkHelpers.FindFreePort ());
2549
2550                         Socket listensock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
2551                         listensock.Bind (endpoint);
2552                         listensock.Listen(1);
2553
2554                         Socket sendsock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
2555                         sendsock.Connect(endpoint);
2556
2557                         Socket clientsock = listensock.Accept();
2558
2559                         byte[] sendbuf = new byte[256];
2560                         List<ArraySegment<byte>> sendbuflist = new List<ArraySegment<byte>>(2);
2561
2562                         sendbuflist.Add(new ArraySegment<byte>(sendbuf, 4, 2));
2563                         sendbuflist.Add(new ArraySegment<byte>(sendbuf, 20, 230));
2564
2565                         for(i = 0; i < 256; i++) {
2566                                 sendbuf[i] = (byte)i;
2567                         }
2568                         for (i = 4; i < 6; i++) {
2569                                 Assert.AreEqual (sendbuf[i], (byte)i,
2570                                                  "#1/" + i.ToString());
2571                         }
2572
2573                         SocketError err;
2574                         sendsock.Send (sendbuflist, SocketFlags.None, out err);
2575
2576                         
2577                         byte[] recvbuf = new byte[256];
2578
2579                         clientsock.Receive (recvbuf);
2580
2581                         /* The first 2 bytes of recvbuf should now
2582                          * hold 2 bytes of sendbuf from pos 4, and the
2583                          * next 230 bytes of recvbuf should be sendbuf
2584                          * from pos 20
2585                          */
2586
2587                         for (i = 0; i < 2; i++) {
2588                                 Assert.AreEqual (recvbuf[i], sendbuf[i + 4],
2589                                                  "#2/" + i.ToString());
2590                         }
2591                         for (i = 2; i < 232; i++) {
2592                                 Assert.AreEqual (recvbuf[i], sendbuf[i + 18],
2593                                                  "#2/" + i.ToString());
2594                         }
2595
2596                         sendsock.Close ();
2597                         clientsock.Close ();
2598                         listensock.Close ();
2599                 }
2600
2601                 [Test]
2602                 public void ListenNotBound ()
2603                 {
2604                         Socket sock = new Socket (AddressFamily.InterNetwork,
2605                                                   SocketType.Stream,
2606                                                   ProtocolType.Tcp);
2607                         
2608                         try {
2609                                 sock.Listen (1);
2610                                 Assert.Fail ("ListenNotBound #1");
2611                         } catch (SocketException ex) {
2612                                 Assert.AreEqual (10022, ex.ErrorCode, "ListenNotBound #2");
2613                         } finally {
2614                                 sock.Close ();
2615                         }
2616                 }
2617
2618                 static Socket CWRSocket;
2619                 static bool CWRReceiving = true;
2620                 static ManualResetEvent CWRReady = new ManualResetEvent (false);
2621                 
2622                 private static void CWRReceiveThread ()
2623                 {
2624                         byte[] buf = new byte[256];
2625                         
2626                         try {
2627                                 CWRSocket.Receive (buf);
2628                         } catch (SocketException) {
2629                                 CWRReceiving = false;
2630                         }
2631
2632                         CWRReady.Set ();
2633                 }
2634                 
2635                 [Test]
2636                 public void CloseWhileReceiving ()
2637                 {
2638                         CWRSocket = new Socket (AddressFamily.InterNetwork,
2639                                                 SocketType.Dgram,
2640                                                 ProtocolType.Udp);
2641                         CWRSocket.Bind (new IPEndPoint (IPAddress.Loopback,
2642                                                         NetworkHelpers.FindFreePort ()));
2643                         
2644                         Thread recv_thread = new Thread (new ThreadStart (CWRReceiveThread));
2645                         CWRReady.Reset ();
2646                         recv_thread.Start ();
2647                         Thread.Sleep (250);     /* Wait for the thread to be already receiving */
2648
2649                         CWRSocket.Close ();
2650                         if (CWRReady.WaitOne (1000, false) == false) {
2651                                 Assert.Fail ("CloseWhileReceiving wait timed out");
2652                         }
2653                         
2654                         Assert.IsFalse (CWRReceiving);
2655                 }
2656
2657                 static bool RRCLastRead = false;
2658                 static ManualResetEvent RRCReady = new ManualResetEvent (false);
2659                 
2660                 private static void RRCClientThread (int port)
2661                 {
2662                         byte[] bytes = new byte[8];
2663                         int readbyte;
2664                         
2665                         Socket sock = new Socket (AddressFamily.InterNetwork,
2666                                                   SocketType.Stream,
2667                                                   ProtocolType.Tcp);
2668                         sock.Connect (new IPEndPoint (IPAddress.Loopback,
2669                                                       port));
2670                         
2671                         NetworkStream stream = new NetworkStream (sock);
2672
2673                         readbyte = stream.ReadByte ();
2674                         Assert.AreEqual (0, readbyte, "ReceiveRemoteClosed #1");
2675                         
2676                         stream.Read (bytes, 0, 0);
2677
2678                         readbyte = stream.ReadByte ();
2679                         Assert.AreEqual (0, readbyte, "ReceiveRemoteClosed #2");
2680                         
2681                         stream.Read (bytes, 0, 0);
2682
2683                         readbyte = stream.ReadByte ();
2684                         Assert.AreEqual (-1, readbyte, "ReceiveRemoteClosed #3");
2685
2686                         sock.Close ();
2687
2688                         RRCLastRead = true;
2689                         RRCReady.Set ();
2690                 }
2691
2692                 [Test] // Receive (Byte [])
2693                 public void Receive1_Buffer_Null ()
2694                 {
2695                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2696                                 ProtocolType.Tcp);
2697
2698                         try {
2699                                 s.Receive ((byte []) null);
2700                                 Assert.Fail ("#1");
2701                         } catch (ArgumentNullException ex) {
2702                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2703                                 Assert.IsNull (ex.InnerException, "#3");
2704                                 Assert.IsNotNull (ex.Message, "#4");
2705                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
2706                         } finally {
2707                                 s.Close ();
2708                         }
2709                 }
2710
2711                 [Test] // Receive (Byte [])
2712                 public void Receive1_Socket_Closed ()
2713                 {
2714                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2715                                 ProtocolType.Tcp);
2716                         s.Close ();
2717
2718                         try {
2719                                 s.Receive ((byte []) null);
2720                                 Assert.Fail ("#1");
2721                         } catch (ObjectDisposedException ex) {
2722                                 // Cannot access a disposed object
2723                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
2724                                 Assert.IsNull (ex.InnerException, "#3");
2725                                 Assert.IsNotNull (ex.Message, "#4");
2726                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
2727                         }
2728                 }
2729
2730                 [Test] // Receive (Byte [], SocketFlags)
2731                 public void Receive2_Buffer_Null ()
2732                 {
2733                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2734                                 ProtocolType.Tcp);
2735
2736                         try {
2737                                 s.Receive ((byte []) null, (SocketFlags) 666);
2738                                 Assert.Fail ("#1");
2739                         } catch (ArgumentNullException ex) {
2740                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2741                                 Assert.IsNull (ex.InnerException, "#3");
2742                                 Assert.IsNotNull (ex.Message, "#4");
2743                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
2744                         } finally {
2745                                 s.Close ();
2746                         }
2747                 }
2748
2749                 [Test] // Receive (Byte [], SocketFlags)
2750                 public void Receive2_Socket_Closed ()
2751                 {
2752                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2753                                 ProtocolType.Tcp);
2754                         s.Close ();
2755
2756                         try {
2757                                 s.Receive ((byte []) null, (SocketFlags) 666);
2758                                 Assert.Fail ("#1");
2759                         } catch (ObjectDisposedException ex) {
2760                                 // Cannot access a disposed object
2761                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
2762                                 Assert.IsNull (ex.InnerException, "#3");
2763                                 Assert.IsNotNull (ex.Message, "#4");
2764                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
2765                         }
2766                 }
2767
2768                 [Test] // Receive (Byte [], Int32, SocketFlags)
2769                 public void Receive3_Buffer_Null ()
2770                 {
2771                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2772                                 ProtocolType.Tcp);
2773
2774                         try {
2775                                 s.Receive ((byte []) null, 0, (SocketFlags) 666);
2776                                 Assert.Fail ("#1");
2777                         } catch (ArgumentNullException ex) {
2778                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2779                                 Assert.IsNull (ex.InnerException, "#3");
2780                                 Assert.IsNotNull (ex.Message, "#4");
2781                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
2782                         } finally {
2783                                 s.Close ();
2784                         }
2785                 }
2786
2787                 [Test] // Receive (Byte [], Int32, SocketFlags)
2788                 public void Receive3_Socket_Closed ()
2789                 {
2790                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2791                                 ProtocolType.Tcp);
2792                         s.Close ();
2793
2794                         try {
2795                                 s.Receive ((byte []) null, 0, (SocketFlags) 666);
2796                                 Assert.Fail ("#1");
2797                         } catch (ObjectDisposedException ex) {
2798                                 // Cannot access a disposed object
2799                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
2800                                 Assert.IsNull (ex.InnerException, "#3");
2801                                 Assert.IsNotNull (ex.Message, "#4");
2802                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
2803                         }
2804                 }
2805
2806                 [Test] // Receive (Byte [], Int32, Int32, SocketFlags)
2807                 public void Receive4_Buffer_Null ()
2808                 {
2809                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2810                                 ProtocolType.Tcp);
2811
2812                         try {
2813                                 s.Receive ((byte []) null, 0, 0, (SocketFlags) 666);
2814                                 Assert.Fail ("#1");
2815                         } catch (ArgumentNullException ex) {
2816                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2817                                 Assert.IsNull (ex.InnerException, "#3");
2818                                 Assert.IsNotNull (ex.Message, "#4");
2819                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
2820                         } finally {
2821                                 s.Close ();
2822                         }
2823                 }
2824
2825                 [Test] // Receive (Byte [], Int32, Int32, SocketFlags)
2826                 public void Receive4_Socket_Closed ()
2827                 {
2828                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2829                                 ProtocolType.Tcp);
2830                         s.Close ();
2831
2832                         try {
2833                                 s.Receive ((byte []) null, 0, 0, (SocketFlags) 666);
2834                                 Assert.Fail ("#1");
2835                         } catch (ObjectDisposedException ex) {
2836                                 // Cannot access a disposed object
2837                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
2838                                 Assert.IsNull (ex.InnerException, "#3");
2839                                 Assert.IsNotNull (ex.Message, "#4");
2840                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
2841                         }
2842                 }
2843
2844                 [Test] // Receive (Byte [], Int32, Int32, SocketFlags, out SocketError)
2845                 public void Receive5_Buffer_Null ()
2846                 {
2847                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2848                                 ProtocolType.Tcp);
2849
2850                         SocketError error;
2851                         try {
2852                                 s.Receive ((byte []) null, 0, 0, SocketFlags.None, out error);
2853                                 Assert.Fail ("#1");
2854                         } catch (ArgumentNullException ex) {
2855                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2856                                 Assert.IsNull (ex.InnerException, "#3");
2857                                 Assert.IsNotNull (ex.Message, "#4");
2858                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
2859                         } finally {
2860                                 s.Close ();
2861                         }
2862                 }
2863
2864                 [Test] // Receive (Byte [], Int32, Int32, SocketFlags, out SocketError)
2865                 public void Receive5_Socket_Closed ()
2866                 {
2867                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2868                                 ProtocolType.Tcp);
2869                         s.Close ();
2870
2871                         SocketError error;
2872                         try {
2873                                 s.Receive ((byte []) null, 0, 0, SocketFlags.None, out error);
2874                                 Assert.Fail ("#1");
2875                         } catch (ObjectDisposedException ex) {
2876                                 // Cannot access a disposed object
2877                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
2878                                 Assert.IsNull (ex.InnerException, "#3");
2879                                 Assert.IsNotNull (ex.Message, "#4");
2880                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
2881                         }
2882                 }
2883
2884                 [Test] // Receive (IList<ArraySegment<Byte>>)
2885                 public void Receive6_Buffers_Null ()
2886                 {
2887                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2888                                 ProtocolType.Tcp);
2889
2890                         try {
2891                                 s.Receive ((IList<ArraySegment<byte>>) null);
2892                                 Assert.Fail ("#1");
2893                         } catch (ArgumentNullException ex) {
2894                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2895                                 Assert.IsNull (ex.InnerException, "#3");
2896                                 Assert.IsNotNull (ex.Message, "#4");
2897                                 Assert.AreEqual ("buffers", ex.ParamName, "#5");
2898                         } finally {
2899                                 s.Close ();
2900                         }
2901                 }
2902
2903                 [Test] // Receive (IList<ArraySegment<Byte>>)
2904                 public void Receive6_Socket_Closed ()
2905                 {
2906                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2907                                 ProtocolType.Tcp);
2908                         s.Close ();
2909
2910                         try {
2911                                 s.Receive ((IList<ArraySegment<byte>>) null);
2912                                 Assert.Fail ("#1");
2913                         } catch (ObjectDisposedException ex) {
2914                                 // Cannot access a disposed object
2915                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
2916                                 Assert.IsNull (ex.InnerException, "#3");
2917                                 Assert.IsNotNull (ex.Message, "#4");
2918                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
2919                         }
2920                 }
2921
2922                 [Test] // Receive (IList<ArraySegment<Byte>>, SocketFlags)
2923                 public void Receive7_Buffers_Null ()
2924                 {
2925                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2926                                 ProtocolType.Tcp);
2927
2928                         try {
2929                                 s.Receive ((IList<ArraySegment<byte>>) null, (SocketFlags) 666);
2930                                 Assert.Fail ("#1");
2931                         } catch (ArgumentNullException ex) {
2932                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2933                                 Assert.IsNull (ex.InnerException, "#3");
2934                                 Assert.IsNotNull (ex.Message, "#4");
2935                                 Assert.AreEqual ("buffers", ex.ParamName, "#5");
2936                         } finally {
2937                                 s.Close ();
2938                         }
2939                 }
2940
2941                 [Test] // Receive (IList<ArraySegment<Byte>>, SocketFlags)
2942                 public void Receive7_Socket_Closed ()
2943                 {
2944                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2945                                 ProtocolType.Tcp);
2946                         s.Close ();
2947
2948                         try {
2949                                 s.Receive ((IList<ArraySegment<byte>>) null, (SocketFlags) 666);
2950                                 Assert.Fail ("#1");
2951                         } catch (ObjectDisposedException ex) {
2952                                 // Cannot access a disposed object
2953                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
2954                                 Assert.IsNull (ex.InnerException, "#3");
2955                                 Assert.IsNotNull (ex.Message, "#4");
2956                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
2957                         }
2958                 }
2959
2960                 [Test] // Receive (IList<ArraySegment<Byte>>, SocketFlags, out SocketError)
2961                 public void Receive8_Buffers_Null ()
2962                 {
2963                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2964                                 ProtocolType.Tcp);
2965
2966                         SocketError error;
2967                         try {
2968                                 s.Receive ((IList<ArraySegment<byte>>) null, (SocketFlags) 666,
2969                                         out error);
2970                                 Assert.Fail ("#1");
2971                         } catch (ArgumentNullException ex) {
2972                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2973                                 Assert.IsNull (ex.InnerException, "#3");
2974                                 Assert.IsNotNull (ex.Message, "#4");
2975                                 Assert.AreEqual ("buffers", ex.ParamName, "#5");
2976                         } finally {
2977                                 s.Close ();
2978                         }
2979                 }
2980
2981                 [Test] // Receive (IList<ArraySegment<Byte>>, SocketFlags, out SocketError)
2982                 public void Receive8_Socket_Closed ()
2983                 {
2984                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2985                                 ProtocolType.Tcp);
2986                         s.Close ();
2987
2988                         SocketError error;
2989                         try {
2990                                 s.Receive ((IList<ArraySegment<byte>>) null, (SocketFlags) 666,
2991                                         out error);
2992                                 Assert.Fail ("#1");
2993                         } catch (ObjectDisposedException ex) {
2994                                 // Cannot access a disposed object
2995                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
2996                                 Assert.IsNull (ex.InnerException, "#3");
2997                                 Assert.IsNotNull (ex.Message, "#4");
2998                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
2999                         } finally {
3000                                 s.Close ();
3001                         }
3002                 }
3003
3004                 [Test] // ReceiveFrom (Byte [], ref EndPoint)
3005                 public void ReceiveFrom1_Buffer_Null ()
3006                 {
3007                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3008                                 ProtocolType.Tcp);
3009
3010                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3011                         try {
3012                                 s.ReceiveFrom ((Byte []) null, ref remoteEP);
3013                                 Assert.Fail ("#1");
3014                         } catch (ArgumentNullException ex) {
3015                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3016                                 Assert.IsNull (ex.InnerException, "#3");
3017                                 Assert.IsNotNull (ex.Message, "#4");
3018                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3019                         } finally {
3020                                 s.Close ();
3021                         }
3022                 }
3023
3024                 [Test] // ReceiveFrom (Byte [], ref EndPoint)
3025                 public void ReceiveFrom1_RemoteEP_Null ()
3026                 {
3027                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3028                                 ProtocolType.Tcp);
3029
3030                         byte [] buffer = new byte [0];
3031                         EndPoint remoteEP = null;
3032                         try {
3033                                 s.ReceiveFrom (buffer, ref remoteEP);
3034                                 Assert.Fail ("#1");
3035                         } catch (ArgumentNullException ex) {
3036                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3037                                 Assert.IsNull (ex.InnerException, "#3");
3038                                 Assert.IsNotNull (ex.Message, "#4");
3039                                 Assert.AreEqual ("remoteEP", ex.ParamName, "#5");
3040                         } finally {
3041                                 s.Close ();
3042                         }
3043                 }
3044
3045                 [Test] // ReceiveFrom (Byte [], ref EndPoint)
3046                 public void ReceiveFrom1_Socket_Closed ()
3047                 {
3048                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3049                                 ProtocolType.Tcp);
3050                         s.Close ();
3051
3052                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3053                         try {
3054                                 s.ReceiveFrom ((Byte []) null, ref remoteEP);
3055                                 Assert.Fail ("#1");
3056                         } catch (ObjectDisposedException ex) {
3057                                 // Cannot access a disposed object
3058                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3059                                 Assert.IsNull (ex.InnerException, "#3");
3060                                 Assert.IsNotNull (ex.Message, "#4");
3061                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3062                         }
3063                 }
3064
3065                 [Test] // ReceiveFrom (Byte [], SocketFlags, ref EndPoint)
3066                 public void ReceiveFrom2_Buffer_Null ()
3067                 {
3068                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3069                                 ProtocolType.Tcp);
3070
3071                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3072                         try {
3073                                 s.ReceiveFrom ((Byte []) null, (SocketFlags) 666, ref remoteEP);
3074                                 Assert.Fail ("#1");
3075                         } catch (ArgumentNullException ex) {
3076                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3077                                 Assert.IsNull (ex.InnerException, "#3");
3078                                 Assert.IsNotNull (ex.Message, "#4");
3079                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3080                         } finally {
3081                                 s.Close ();
3082                         }
3083                 }
3084
3085                 [Test] // ReceiveFrom (Byte [], SocketFlags, ref EndPoint)
3086                 public void ReceiveFrom2_RemoteEP_Null ()
3087                 {
3088                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3089                                 ProtocolType.Tcp);
3090
3091                         byte [] buffer = new byte [5];
3092                         EndPoint remoteEP = null;
3093                         try {
3094                                 s.ReceiveFrom (buffer, (SocketFlags) 666, ref remoteEP);
3095                                 Assert.Fail ("#1");
3096                         } catch (ArgumentNullException ex) {
3097                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3098                                 Assert.IsNull (ex.InnerException, "#3");
3099                                 Assert.IsNotNull (ex.Message, "#4");
3100                                 Assert.AreEqual ("remoteEP", ex.ParamName, "#5");
3101                         } finally {
3102                                 s.Close ();
3103                         }
3104                 }
3105
3106                 [Test] // ReceiveFrom (Byte [], SocketFlags, ref EndPoint)
3107                 public void ReceiveFrom2_Socket_Closed ()
3108                 {
3109                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3110                                 ProtocolType.Tcp);
3111                         s.Close ();
3112
3113                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3114                         try {
3115                                 s.ReceiveFrom ((Byte []) null, (SocketFlags) 666, ref remoteEP);
3116                                 Assert.Fail ("#1");
3117                         } catch (ObjectDisposedException ex) {
3118                                 // Cannot access a disposed object
3119                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3120                                 Assert.IsNull (ex.InnerException, "#3");
3121                                 Assert.IsNotNull (ex.Message, "#4");
3122                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3123                         }
3124                 }
3125
3126                 [Test] // ReceiveFrom (Byte [], Int32, SocketFlags, ref EndPoint)
3127                 public void ReceiveFrom3_Buffer_Null ()
3128                 {
3129                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3130                                 ProtocolType.Tcp);
3131
3132                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3133                         try {
3134                                 s.ReceiveFrom ((Byte []) null, 0, (SocketFlags) 666,
3135                                         ref remoteEP);
3136                                 Assert.Fail ("#1");
3137                         } catch (ArgumentNullException ex) {
3138                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3139                                 Assert.IsNull (ex.InnerException, "#3");
3140                                 Assert.IsNotNull (ex.Message, "#4");
3141                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3142                         } finally {
3143                                 s.Close ();
3144                         }
3145                 }
3146
3147                 [Test] // ReceiveFrom (Byte [], Int32, SocketFlags, ref EndPoint)
3148                 public void ReceiveFrom3_RemoteEP_Null ()
3149                 {
3150                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3151                                 ProtocolType.Tcp);
3152
3153                         byte [] buffer = new byte [5];
3154                         EndPoint remoteEP = null;
3155                         try {
3156                                 s.ReceiveFrom (buffer, buffer.Length, (SocketFlags) 666, ref remoteEP);
3157                                 Assert.Fail ("#1");
3158                         } catch (ArgumentNullException ex) {
3159                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3160                                 Assert.IsNull (ex.InnerException, "#3");
3161                                 Assert.IsNotNull (ex.Message, "#4");
3162                                 Assert.AreEqual ("remoteEP", ex.ParamName, "#5");
3163                         } finally {
3164                                 s.Close ();
3165                         }
3166                 }
3167
3168                 [Test] // ReceiveFrom (Byte [], Int32, SocketFlags, ref EndPoint)
3169                 public void ReceiveFrom3_Size_OutOfRange ()
3170                 {
3171                         Socket s;
3172                         byte [] buffer = new byte [5];
3173                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3174
3175                         // size negative
3176                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3177                                                         ProtocolType.Tcp);
3178                         try {
3179                                 s.ReceiveFrom (buffer, -1, (SocketFlags) 666, ref remoteEP);
3180                                 Assert.Fail ("#A1");
3181                         } catch (ArgumentOutOfRangeException ex) {
3182                                 // Specified argument was out of the range of valid values
3183                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
3184                                 Assert.IsNull (ex.InnerException, "#A3");
3185                                 Assert.IsNotNull (ex.Message, "#A4");
3186                                 Assert.AreEqual ("size", ex.ParamName, "#A5");
3187                         } finally {
3188                                 s.Close ();
3189                         }
3190
3191                         // size > buffer length
3192                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3193                                                         ProtocolType.Tcp);
3194                         try {
3195                                 s.ReceiveFrom (buffer, (buffer.Length + 1), (SocketFlags) 666,
3196                                         ref remoteEP);
3197                                 Assert.Fail ("#B1");
3198                         } catch (ArgumentOutOfRangeException ex) {
3199                                 // Specified argument was out of the range of valid values
3200                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#B2");
3201                                 Assert.IsNull (ex.InnerException, "#B3");
3202                                 Assert.IsNotNull (ex.Message, "#B4");
3203                                 Assert.AreEqual ("size", ex.ParamName, "#B5");
3204                         } finally {
3205                                 s.Close ();
3206                         }
3207                 }
3208
3209                 [Test] // ReceiveFrom (Byte [], Int32, SocketFlags, ref EndPoint)
3210                 public void ReceiveFrom3_Socket_Closed ()
3211                 {
3212                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3213                                 ProtocolType.Tcp);
3214                         s.Close ();
3215
3216                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3217                         try {
3218                                 s.ReceiveFrom ((Byte []) null, -1, (SocketFlags) 666,
3219                                         ref remoteEP);
3220                                 Assert.Fail ("#1");
3221                         } catch (ObjectDisposedException ex) {
3222                                 // Cannot access a disposed object
3223                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3224                                 Assert.IsNull (ex.InnerException, "#3");
3225                                 Assert.IsNotNull (ex.Message, "#4");
3226                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3227                         }
3228                 }
3229
3230                 [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, EndPoint)
3231                 public void ReceiveFrom4_Buffer_Null ()
3232                 {
3233                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3234                                 ProtocolType.Tcp);
3235                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3236
3237                         try {
3238                                 s.ReceiveFrom ((Byte []) null, -1, -1, (SocketFlags) 666,
3239                                         ref remoteEP);
3240                                 Assert.Fail ("#1");
3241                         } catch (ArgumentNullException ex) {
3242                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3243                                 Assert.IsNull (ex.InnerException, "#3");
3244                                 Assert.IsNotNull (ex.Message, "#4");
3245                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3246                         }
3247                 }
3248
3249                 [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, EndPoint)
3250                 public void ReceiveFrom4_Offset_OutOfRange ()
3251                 {
3252                         Socket s;
3253                         byte [] buffer = new byte [5];
3254                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3255
3256                         // offset negative
3257                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3258                                                         ProtocolType.Tcp);
3259                         try {
3260                                 s.ReceiveFrom (buffer, -1, 0, (SocketFlags) 666,
3261                                         ref remoteEP);
3262                                 Assert.Fail ("#A1");
3263                         } catch (ArgumentOutOfRangeException ex) {
3264                                 // Specified argument was out of the range of valid values
3265                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
3266                                 Assert.IsNull (ex.InnerException, "#A3");
3267                                 Assert.IsNotNull (ex.Message, "#A4");
3268                                 Assert.AreEqual ("offset", ex.ParamName, "#A5");
3269                         } finally {
3270                                 s.Close ();
3271                         }
3272
3273                         // offset > buffer length
3274                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3275                                                         ProtocolType.Tcp);
3276                         try {
3277                                 s.ReceiveFrom (buffer, (buffer.Length + 1), 0, (SocketFlags) 666,
3278                                         ref remoteEP);
3279                                 Assert.Fail ("#B1");
3280                         } catch (ArgumentOutOfRangeException ex) {
3281                                 // Specified argument was out of the range of valid values
3282                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#B2");
3283                                 Assert.IsNull (ex.InnerException, "#B3");
3284                                 Assert.IsNotNull (ex.Message, "#B4");
3285                                 Assert.AreEqual ("offset", ex.ParamName, "#B5");
3286                         } finally {
3287                                 s.Close ();
3288                         }
3289                 }
3290
3291                 [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, ref IPEndPoint)
3292                 public void ReceiveFrom4_RemoteEP_Null ()
3293                 {
3294                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3295                                 ProtocolType.Tcp);
3296                         byte [] buffer = new byte [5];
3297                         EndPoint remoteEP = null;
3298
3299                         try {
3300                                 s.ReceiveFrom (buffer, 0, buffer.Length, (SocketFlags) 666, ref remoteEP);
3301                                 Assert.Fail ("#1");
3302                         } catch (ArgumentNullException ex) {
3303                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3304                                 Assert.IsNull (ex.InnerException, "#3");
3305                                 Assert.IsNotNull (ex.Message, "#4");
3306                                 Assert.AreEqual ("remoteEP", ex.ParamName, "#5");
3307                         } finally {
3308                                 s.Close ();
3309                         }
3310                 }
3311
3312                 [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, EndPoint)
3313                 public void ReceiveFrom4_Size_OutOfRange ()
3314                 {
3315                         Socket s;
3316                         byte [] buffer = new byte [5];
3317                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3318
3319                         // size negative
3320                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3321                                                         ProtocolType.Tcp);
3322                         try {
3323                                 s.ReceiveFrom (buffer, 0, -1, (SocketFlags) 666,
3324                                         ref remoteEP);
3325                                 Assert.Fail ("#A1");
3326                         } catch (ArgumentOutOfRangeException ex) {
3327                                 // Specified argument was out of the range of valid values
3328                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
3329                                 Assert.IsNull (ex.InnerException, "#A3");
3330                                 Assert.IsNotNull (ex.Message, "#A4");
3331                                 Assert.AreEqual ("size", ex.ParamName, "#A5");
3332                         } finally {
3333                                 s.Close ();
3334                         }
3335
3336                         // size > buffer length
3337                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3338                                                         ProtocolType.Tcp);
3339                         try {
3340                                 s.ReceiveFrom (buffer, 0, (buffer.Length + 1), (SocketFlags) 666,
3341                                         ref remoteEP);
3342                                 Assert.Fail ("#B1");
3343                         } catch (ArgumentOutOfRangeException ex) {
3344                                 // Specified argument was out of the range of valid values
3345                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#B2");
3346                                 Assert.IsNull (ex.InnerException, "#B3");
3347                                 Assert.IsNotNull (ex.Message, "#B4");
3348                                 Assert.AreEqual ("size", ex.ParamName, "#B5");
3349                         } finally {
3350                                 s.Close ();
3351                         }
3352
3353                         // offset + size > buffer length
3354                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3355                                                         ProtocolType.Tcp);
3356                         try {
3357                                 s.ReceiveFrom (buffer, 2, 4, (SocketFlags) 666, ref remoteEP);
3358                                 Assert.Fail ("#C1");
3359                         } catch (ArgumentOutOfRangeException ex) {
3360                                 // Specified argument was out of the range of valid values
3361                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#C2");
3362                                 Assert.IsNull (ex.InnerException, "#C3");
3363                                 Assert.IsNotNull (ex.Message, "#C4");
3364                                 Assert.AreEqual ("size", ex.ParamName, "#C5");
3365                         } finally {
3366                                 s.Close ();
3367                         }
3368                 }
3369
3370                 [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, ref EndPoint)
3371                 public void ReceiveFrom4_Socket_Closed ()
3372                 {
3373                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3374                                 ProtocolType.Tcp);
3375                         s.Close ();
3376
3377                         byte [] buffer = new byte [5];
3378                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3379                         try {
3380                                 s.ReceiveFrom (buffer, -1, -1, (SocketFlags) 666,
3381                                         ref remoteEP);
3382                                 Assert.Fail ("#1");
3383                         } catch (ObjectDisposedException ex) {
3384                                 // Cannot access a disposed object
3385                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3386                                 Assert.IsNull (ex.InnerException, "#3");
3387                                 Assert.IsNotNull (ex.Message, "#4");
3388                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3389                         }
3390                 }
3391
3392                 [Test]
3393                 public void ReceiveRemoteClosed ()
3394                 {
3395                         var port = NetworkHelpers.FindFreePort ();
3396                         Socket sock = new Socket (AddressFamily.InterNetwork,
3397                                                   SocketType.Stream,
3398                                                   ProtocolType.Tcp);
3399                         sock.Bind (new IPEndPoint (IPAddress.Loopback, port));
3400                         sock.Listen (1);
3401                         
3402                         RRCReady.Reset ();
3403                         Thread client_thread = new Thread (() => RRCClientThread (port));
3404                         client_thread.Start ();
3405                         
3406                         Socket client = sock.Accept ();
3407                         NetworkStream stream = new NetworkStream (client);
3408                         stream.WriteByte (0x00);
3409                         stream.WriteByte (0x00);
3410                         client.Close ();
3411                         sock.Close ();
3412
3413                         RRCReady.WaitOne (1000, false);
3414                         Assert.IsTrue (RRCLastRead);
3415                 }
3416
3417                 //
3418                 // Test case for bug #471580
3419                 [Test]
3420                 public void UdpDoubleBind ()
3421                 {
3422                         using (Socket s = new Socket (AddressFamily.InterNetwork,
3423                                                 SocketType.Dgram, ProtocolType.Udp))
3424                         using (Socket ss = new Socket (AddressFamily.InterNetwork,
3425                                                 SocketType.Dgram, ProtocolType.Udp)) {
3426                                 var supportsReuseAddress = true;
3427                                 try {
3428                                         s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
3429                                 } catch (SocketException e) {
3430                                         // Exception is thrown when ReuseAddress is not supported
3431                                         Assert.AreEqual ((int) SocketError.OperationNotSupported, e.NativeErrorCode,
3432                                                         "Expected SocketError.OperationNotSupported");
3433                                         supportsReuseAddress = false;
3434                                 }
3435
3436                                 var ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
3437                                 s.Bind (ep);
3438
3439                                 if (supportsReuseAddress)
3440                                         ss.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
3441
3442                                 try {
3443                                         ss.Bind (new IPEndPoint (IPAddress.Any, ep.Port));
3444                                         if (!supportsReuseAddress)
3445                                                 Assert.Fail ("Reusing address is not supported, exception was expected on second bind.");
3446                                 } catch (SocketException e) {
3447                                 }
3448                         }
3449                 }
3450
3451                 // Test case for bug #31557
3452                 [Test]
3453                 public void TcpDoubleBind ()
3454                 {
3455                         using (Socket s = new Socket (AddressFamily.InterNetwork,
3456                                                 SocketType.Stream, ProtocolType.Tcp))
3457                         using (Socket ss = new Socket (AddressFamily.InterNetwork,
3458                                                 SocketType.Stream, ProtocolType.Tcp)) {
3459                                 var supportsReuseAddress = true;
3460                                 try {
3461                                         s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
3462                                 } catch (SocketException e) {
3463                                         // Exception is thrown when ReuseAddress is not supported
3464                                         Assert.AreEqual ((int) SocketError.OperationNotSupported, e.NativeErrorCode,
3465                                                         "Expected SocketError.OperationNotSupported");
3466                                         supportsReuseAddress = false;
3467                                 }
3468
3469                                 var ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
3470                                 s.Bind (ep);
3471                                 s.Listen(1);
3472
3473                                 if (supportsReuseAddress)
3474                                         ss.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
3475
3476                                 try {
3477                                         ss.Bind (new IPEndPoint (IPAddress.Any, ep.Port));
3478                                         ss.Listen(1);
3479                                         if (!supportsReuseAddress)
3480                                                 Assert.Fail ("Reusing address is not supported, exception was expected on second bind.");
3481                                 } catch (SocketException e) {
3482                                 }
3483                         }
3484                 }
3485
3486                 [Test]
3487                 [Category ("NotOnMac")]
3488                 public void ConnectedProperty ()
3489                 {
3490                         TcpListener listener = new TcpListener (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3491                         listener.Start();
3492
3493                         Socket client = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3494                         client.Connect (IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
3495                         Socket server = listener.AcceptSocket ();
3496
3497                         try {
3498                                 server.EndSend(server.BeginSend (new byte[10], 0, 10, SocketFlags.None, null, null));
3499                                 client.Close ();
3500                                 try {
3501                                         server.EndReceive (server.BeginReceive (new byte[10], 0, 10, SocketFlags.None, null, null));
3502                                 } catch {
3503                                 }
3504                                 Assert.IsTrue (!client.Connected);
3505                                 Assert.IsTrue (!server.Connected);
3506                         } finally {
3507                                 listener.Stop ();
3508                                 client.Close ();
3509                                 server.Close ();
3510                         }
3511                 }
3512
3513                 [Test] // GetSocketOption (SocketOptionLevel, SocketOptionName)
3514                 public void GetSocketOption1_Socket_Closed ()
3515                 {
3516                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3517                         s.Close ();
3518                         try {
3519                                 s.GetSocketOption (0, 0);
3520                                 Assert.Fail ("#1");
3521                         } catch (ObjectDisposedException ex) {
3522                                 // Cannot access a disposed object
3523                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3524                                 Assert.IsNull (ex.InnerException, "#3");
3525                                 Assert.IsNotNull (ex.Message, "#4");
3526                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3527                         }
3528                 }
3529
3530                 [Test] // GetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3531                 public void GetSocketOption2_OptionValue_Null ()
3532                 {
3533                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3534                         try {
3535                                 s.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
3536                                         (byte []) null);
3537                                 Assert.Fail ("#1");
3538                                 } catch (SocketException ex) {
3539                                         // The system detected an invalid pointer address in attempting
3540                                         // to use a pointer argument in a call
3541                                         Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
3542                                         Assert.AreEqual (10014, ex.ErrorCode, "#3");
3543                                         Assert.IsNull (ex.InnerException, "#4");
3544                                         Assert.IsNotNull (ex.Message, "#5");
3545                                         Assert.AreEqual (10014, ex.NativeErrorCode, "#6");
3546                                         Assert.AreEqual (SocketError.Fault, ex.SocketErrorCode, "#7");
3547                                 }
3548                 }
3549
3550                 [Test] // GetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3551                 public void GetSocketOption2_Socket_Closed ()
3552                 {
3553                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3554                         s.Close ();
3555                         try {
3556                                 s.GetSocketOption (0, 0, (byte []) null);
3557                                 Assert.Fail ("#1");
3558                         } catch (ObjectDisposedException ex) {
3559                                 // Cannot access a disposed object
3560                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3561                                 Assert.IsNull (ex.InnerException, "#3");
3562                                 Assert.IsNotNull (ex.Message, "#4");
3563                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3564                         }
3565                 }
3566
3567                 [Test] // GetSocketOption (SocketOptionLevel, SocketOptionName, Int32)
3568                 public void GetSocketOption3_Socket_Closed ()
3569                 {
3570                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3571                         s.Close ();
3572                         try {
3573                                 s.GetSocketOption (0, 0, 0);
3574                                 Assert.Fail ("#1");
3575                         } catch (ObjectDisposedException ex) {
3576                                 // Cannot access a disposed object
3577                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3578                                 Assert.IsNull (ex.InnerException, "#3");
3579                                 Assert.IsNotNull (ex.Message, "#4");
3580                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3581                         }
3582                 }
3583
3584                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3585                 public void SetSocketOption1_DontLinger ()
3586                 {
3587                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3588                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger,
3589                                         new byte [] { 0x00 });
3590                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger,
3591                                         new byte [] { 0x01 });
3592                         }
3593                 }
3594
3595                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3596                 public void SetSocketOption1_DontLinger_Null ()
3597                 {
3598                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3599                                 try {
3600                                         s.SetSocketOption (SocketOptionLevel.Socket,
3601                                                 SocketOptionName.DontLinger, (byte []) null);
3602                                         Assert.Fail ("#1");
3603                                 } catch (SocketException ex) {
3604                                         // The system detected an invalid pointer address in attempting
3605                                         // to use a pointer argument in a call
3606                                         Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
3607                                         Assert.AreEqual (10014, ex.ErrorCode, "#3");
3608                                         Assert.IsNull (ex.InnerException, "#4");
3609                                         Assert.IsNotNull (ex.Message, "#5");
3610                                         Assert.AreEqual (10014, ex.NativeErrorCode, "#6");
3611                                         Assert.AreEqual (SocketError.Fault, ex.SocketErrorCode, "#7");
3612                                 }
3613                         }
3614                 }
3615
3616                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3617                 public void SetSocketOption1_Linger_Null ()
3618                 {
3619                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3620                                 try {
3621                                         s.SetSocketOption (SocketOptionLevel.Socket,
3622                                                 SocketOptionName.DontLinger, (byte []) null);
3623                                         Assert.Fail ("#1");
3624                                 } catch (SocketException ex) {
3625                                         // The system detected an invalid pointer address in attempting
3626                                         // to use a pointer argument in a call
3627                                         Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
3628                                         Assert.AreEqual (10014, ex.ErrorCode, "#3");
3629                                         Assert.IsNull (ex.InnerException, "#4");
3630                                         Assert.IsNotNull (ex.Message, "#5");
3631                                         Assert.AreEqual (10014, ex.NativeErrorCode, "#6");
3632                                         Assert.AreEqual (SocketError.Fault, ex.SocketErrorCode, "#7");
3633                                 }
3634                         }
3635                 }
3636
3637                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3638                 public void SetSocketOption1_Socket_Close ()
3639                 {
3640                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3641                         s.Close ();
3642                         try {
3643                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger,
3644                                         new byte [] { 0x00 });
3645                                 Assert.Fail ("#1");
3646                         } catch (ObjectDisposedException ex) {
3647                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3648                                 Assert.IsNull (ex.InnerException, "#3");
3649                                 Assert.IsNotNull (ex.Message, "#4");
3650                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3651                         }
3652                 }
3653
3654                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Int32)
3655                 public void SetSocketOption2_DontLinger ()
3656                 {
3657                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3658                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger, 0);
3659                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger, 5);
3660                         }
3661                 }
3662
3663                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Int32)
3664                 [Category ("NotWorking")]
3665                 public void SetSocketOption2_Linger ()
3666                 {
3667                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3668                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger, 0);
3669                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger, 5);
3670                         }
3671                 }
3672
3673                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Int32)
3674                 public void SetSocketOption2_Socket_Closed ()
3675                 {
3676                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3677                         s.Close ();
3678                         try {
3679                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger, 0);
3680                                 Assert.Fail ("#1");
3681                         } catch (ObjectDisposedException ex) {
3682                                 // Cannot access a disposed object
3683                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3684                                 Assert.IsNull (ex.InnerException, "#3");
3685                                 Assert.IsNotNull (ex.Message, "#4");
3686                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3687                         }
3688                 }
3689
3690                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3691                 public void SetSocketOption3_AddMembershipIPv4_IPv6MulticastOption ()
3692                 {
3693                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
3694
3695                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
3696                                 s.Bind (new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ()));
3697                                 try {
3698                                         s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
3699                                                 new IPv6MulticastOption (mcast_addr));
3700                                         Assert.Fail ("#1");
3701                                 } catch (ArgumentException ex) {
3702                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
3703                                         Assert.IsNull (ex.InnerException, "#3");
3704                                         Assert.IsNotNull (ex.Message, "#4");
3705                                         // The specified value is not a valid 'MulticastOption'
3706                                         Assert.IsTrue (ex.Message.IndexOf ("'MulticastOption'") != -1, "#5:" + ex.Message);
3707                                         Assert.AreEqual ("optionValue", ex.ParamName, "#6");
3708                                 }
3709                         }
3710                 }
3711
3712                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3713                 public void SetSocketOption3_AddMembershipIPv4_MulticastOption ()
3714                 {
3715                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
3716
3717                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
3718                                 s.Bind (new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ()));
3719                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
3720                                         new MulticastOption (mcast_addr));
3721                         }
3722                 }
3723
3724                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3725                 [Category ("NotWorking")]
3726                 public void SetSocketOption3_AddMembershipIPv4_Socket_NotBound ()
3727                 {
3728                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
3729
3730                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
3731                         try {
3732                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
3733                                         new MulticastOption (mcast_addr));
3734                                 Assert.Fail ("#1");
3735                         } catch (SocketException ex) {
3736                                 // An invalid argument was supplied
3737                                 Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
3738                                 Assert.AreEqual (10022, ex.ErrorCode, "#3");
3739                                 Assert.IsNull (ex.InnerException, "#4");
3740                                 Assert.IsNotNull (ex.Message, "#5");
3741                                 Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
3742                                 Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
3743                         } finally {
3744                                 s.Close ();
3745                         }
3746                 }
3747
3748                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3749                 public void SetSocketOption3_AddMembershipIPv6_IPv6MulticastOption ()
3750                 {
3751                         if (!Socket.OSSupportsIPv6)
3752                                 Assert.Ignore ("IPv6 not enabled.");
3753
3754                         IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
3755
3756                         using (Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp)) {
3757                                 s.Bind (new IPEndPoint (IPAddress.IPv6Any, NetworkHelpers.FindFreePort ()));
3758                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
3759                                         new IPv6MulticastOption (mcast_addr));
3760                         }
3761                 }
3762
3763                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3764                 public void SetSocketOption3_AddMembershipIPv6_MulticastOption ()
3765                 {
3766                         if (!Socket.OSSupportsIPv6)
3767                                 Assert.Ignore ("IPv6 not enabled.");
3768
3769                         IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
3770
3771                         using (Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp)) {
3772                                 s.Bind (new IPEndPoint (IPAddress.IPv6Any, NetworkHelpers.FindFreePort ()));
3773                                 try {
3774                                         s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
3775                                                 new MulticastOption (mcast_addr));
3776                                         Assert.Fail ("#1");
3777                                 } catch (ArgumentException ex) {
3778                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
3779                                         Assert.IsNull (ex.InnerException, "#3");
3780                                         Assert.IsNotNull (ex.Message, "#4");
3781                                         // The specified value is not a valid 'IPv6MulticastOption'
3782                                         Assert.IsTrue (ex.Message.IndexOf ("'IPv6MulticastOption'") != -1, "#5:" + ex.Message);
3783                                         Assert.AreEqual ("optionValue", ex.ParamName, "#6");
3784                                 }
3785                         }
3786                 }
3787
3788                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3789                 [Category ("NotWorking")]
3790                 public void SetSocketOption3_AddMembershipIPv6_Socket_NotBound ()
3791                 {
3792                         IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
3793
3794                         Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
3795                         try {
3796                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
3797                                         new IPv6MulticastOption (mcast_addr));
3798                                 Assert.Fail ("#1");
3799                         } catch (SocketException ex) {
3800                                 // An invalid argument was supplied
3801                                 Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
3802                                 Assert.AreEqual (10022, ex.ErrorCode, "#3");
3803                                 Assert.IsNull (ex.InnerException, "#4");
3804                                 Assert.IsNotNull (ex.Message, "#5");
3805                                 Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
3806                                 Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
3807                         } finally {
3808                                 s.Close ();
3809                         }
3810                 }
3811
3812                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3813                 public void SetSocketOption3_DontLinger_Boolean ()
3814                 {
3815                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3816                                 try {
3817                                         s.SetSocketOption (SocketOptionLevel.Socket,
3818                                                 SocketOptionName.DontLinger, (object) false);
3819                                         Assert.Fail ("#1");
3820                                 } catch (ArgumentException ex) {
3821                                         // The specified value is not valid
3822                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
3823                                         Assert.IsNull (ex.InnerException, "#3");
3824                                         Assert.IsNotNull (ex.Message, "#4");
3825                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
3826                                 }
3827                         }
3828                 }
3829
3830                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3831                 public void SetSocketOption3_DontLinger_Int32 ()
3832                 {
3833                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3834                                 try {
3835                                         s.SetSocketOption (SocketOptionLevel.Socket,
3836                                                 SocketOptionName.DontLinger, (object) 0);
3837                                         Assert.Fail ("#1");
3838                                 } catch (ArgumentException ex) {
3839                                         // The specified value is not valid
3840                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
3841                                         Assert.IsNull (ex.InnerException, "#3");
3842                                         Assert.IsNotNull (ex.Message, "#4");
3843                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
3844                                 }
3845                         }
3846                 }
3847
3848                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3849                 public void SetSocketOption3_DontLinger_LingerOption ()
3850                 {
3851                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3852                                 try {
3853                                         s.SetSocketOption (SocketOptionLevel.Socket,
3854                                                 SocketOptionName.DontLinger, new LingerOption (true, 1000));
3855                                         Assert.Fail ("#1");
3856                                 } catch (ArgumentException ex) {
3857                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
3858                                         Assert.IsNull (ex.InnerException, "#3");
3859                                         // The specified value is not valid
3860                                         Assert.IsNotNull (ex.Message, "#4");
3861                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
3862                                 }
3863                         }
3864                 }
3865
3866                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3867                 public void SetSocketOption3_Linger_Boolean ()
3868                 {
3869                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3870                                 try {
3871                                         s.SetSocketOption (SocketOptionLevel.Socket,
3872                                                 SocketOptionName.Linger, (object) false);
3873                                         Assert.Fail ("#1");
3874                                 } catch (ArgumentException ex) {
3875                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
3876                                         Assert.IsNull (ex.InnerException, "#3");
3877                                         // The specified value is not valid
3878                                         Assert.IsNotNull (ex.Message, "#4");
3879                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
3880                                 }
3881                         }
3882                 }
3883
3884                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3885                 public void SetSocketOption3_Linger_Int32 ()
3886                 {
3887                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3888                                 try {
3889                                         s.SetSocketOption (SocketOptionLevel.Socket,
3890                                                 SocketOptionName.Linger, (object) 0);
3891                                         Assert.Fail ("#1");
3892                                 } catch (ArgumentException ex) {
3893                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
3894                                         Assert.IsNull (ex.InnerException, "#3");
3895                                         // The specified value is not valid
3896                                         Assert.IsNotNull (ex.Message, "#4");
3897                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
3898                                 }
3899                         }
3900                 }
3901
3902                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3903                 public void SetSocketOption3_Linger_LingerOption ()
3904                 {
3905                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3906                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
3907                                         new LingerOption (false, 0));
3908                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
3909                                         new LingerOption (true, 0));
3910                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
3911                                         new LingerOption (false, 1000));
3912                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
3913                                         new LingerOption (true, 1000));
3914                         }
3915                 }
3916
3917                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3918                 public void SetSocketOption3_DropMembershipIPv4_IPv6MulticastOption ()
3919                 {
3920                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
3921
3922                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
3923                                 s.Bind (new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ()));
3924                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
3925                                         new MulticastOption (mcast_addr));
3926                                 try {
3927                                         s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
3928                                                 new IPv6MulticastOption (mcast_addr));
3929                                         Assert.Fail ("#1");
3930                                 } catch (ArgumentException ex) {
3931                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
3932                                         Assert.IsNull (ex.InnerException, "#3");
3933                                         Assert.IsNotNull (ex.Message, "#4");
3934                                         // The specified value is not a valid 'MulticastOption'
3935                                         Assert.IsTrue (ex.Message.IndexOf ("'MulticastOption'") != -1, "#5:" + ex.Message);
3936                                         Assert.AreEqual ("optionValue", ex.ParamName, "#6");
3937                                 }
3938                         }
3939                 }
3940
3941                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3942                 public void SetSocketOption3_DropMembershipIPv4_MulticastOption ()
3943                 {
3944                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
3945
3946                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
3947                                 MulticastOption option = new MulticastOption (mcast_addr);
3948
3949                                 s.Bind (new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ()));
3950                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
3951                                         option);
3952                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
3953                                         option);
3954                         }
3955                 }
3956
3957                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3958                 [Category ("NotWorking")]
3959                 public void SetSocketOption3_DropMembershipIPv4_Socket_NotBound ()
3960                 {
3961                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
3962
3963                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
3964                         try {
3965                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
3966                                         new MulticastOption (mcast_addr));
3967                                 Assert.Fail ("#1");
3968                         } catch (SocketException ex) {
3969                                 // An invalid argument was supplied
3970                                 Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
3971                                 Assert.AreEqual (10022, ex.ErrorCode, "#3");
3972                                 Assert.IsNull (ex.InnerException, "#4");
3973                                 Assert.IsNotNull (ex.Message, "#5");
3974                                 Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
3975                                 Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
3976                         } finally {
3977                                 s.Close ();
3978                         }
3979                 }
3980
3981                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3982                 public void SetSocketOption3_DropMembershipIPv6_IPv6MulticastOption ()
3983                 {
3984                         if (!Socket.OSSupportsIPv6)
3985                                 Assert.Ignore ("IPv6 not enabled.");
3986
3987                         using (Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp)) {
3988                                 IPv6MulticastOption option = new IPv6MulticastOption (
3989                                         IPAddress.Parse ("ff02::1"));
3990
3991                                 s.Bind (new IPEndPoint (IPAddress.IPv6Any, 1902));
3992                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
3993                                         option);
3994                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
3995                                         option);
3996                         }
3997                 }
3998
3999                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4000                 public void SetSocketOption3_DropMembershipIPv6_MulticastOption ()
4001                 {
4002                         if (!Socket.OSSupportsIPv6)
4003                                 Assert.Ignore ("IPv6 not enabled.");
4004
4005                         IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
4006
4007                         using (Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp)) {
4008                                 s.Bind (new IPEndPoint (IPAddress.IPv6Any, NetworkHelpers.FindFreePort ()));
4009                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
4010                                         new IPv6MulticastOption (mcast_addr));
4011                                 try {
4012                                         s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
4013                                                 new MulticastOption (mcast_addr));
4014                                         Assert.Fail ("#1");
4015                                 } catch (ArgumentException ex) {
4016                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
4017                                         Assert.IsNull (ex.InnerException, "#3");
4018                                         Assert.IsNotNull (ex.Message, "#4");
4019                                         // The specified value is not a valid 'IPv6MulticastOption'
4020                                         Assert.IsTrue (ex.Message.IndexOf ("'IPv6MulticastOption'") != -1, "#5:" + ex.Message);
4021                                         Assert.AreEqual ("optionValue", ex.ParamName, "#6");
4022                                 }
4023                         }
4024                 }
4025
4026                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4027                 [Category ("NotWorking")]
4028                 public void SetSocketOption3_DropMembershipIPv6_Socket_NotBound ()
4029                 {
4030                         IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
4031
4032                         Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
4033                         try {
4034                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
4035                                         new IPv6MulticastOption (mcast_addr));
4036                                 Assert.Fail ("#1");
4037                         } catch (SocketException ex) {
4038                                 // An invalid argument was supplied
4039                                 Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
4040                                 Assert.AreEqual (10022, ex.ErrorCode, "#3");
4041                                 Assert.IsNull (ex.InnerException, "#4");
4042                                 Assert.IsNotNull (ex.Message, "#5");
4043                                 Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
4044                                 Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
4045                         } finally {
4046                                 s.Close ();
4047                         }
4048                 }
4049
4050                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4051                 public void SetSocketOption3_OptionValue_Null ()
4052                 {
4053                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4054                                 try {
4055                                         s.SetSocketOption (SocketOptionLevel.Socket,
4056                                                 SocketOptionName.Linger, (object) null);
4057                                         Assert.Fail ("#1");
4058                                 } catch (ArgumentNullException ex) {
4059                                         Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
4060                                         Assert.IsNull (ex.InnerException, "#3");
4061                                         Assert.IsNotNull (ex.Message, "#4");
4062                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
4063                                 }
4064                         }
4065                 }
4066
4067                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4068                 public void SetSocketOption3_Socket_Closed ()
4069                 {
4070                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4071                         s.Close ();
4072                         try {
4073                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
4074                                         new LingerOption (false, 0));
4075                                 Assert.Fail ("#1");
4076                         } catch (ObjectDisposedException ex) {
4077                                 // Cannot access a disposed object
4078                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
4079                                 Assert.IsNull (ex.InnerException, "#3");
4080                                 Assert.IsNotNull (ex.Message, "#4");
4081                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
4082                         }
4083                 }
4084
4085                 [Test]
4086                 public void SetSocketOption_MulticastInterfaceIndex_Any ()
4087                 {
4088                         IPAddress ip = IPAddress.Parse ("239.255.255.250");
4089                         int index = 0;
4090                         using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
4091                         {
4092                                 s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(index));
4093                                 s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, index));
4094                         }
4095                 }
4096
4097                 [Test]
4098                 public void SetSocketOption_MulticastInterfaceIndex_Loopback ()
4099                 {
4100                         IPAddress ip = IPAddress.Parse ("239.255.255.250");
4101                         int index = 1;
4102                         using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
4103                         {
4104                                 s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(index));
4105                                 s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, index));
4106                         }
4107                 }
4108
4109                 [Test]
4110                 public void SetSocketOption_MulticastInterfaceIndex_Invalid ()
4111                 {
4112                         IPAddress ip = IPAddress.Parse ("239.255.255.250");
4113                         int index = 31415;
4114                         using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
4115                         {
4116                                 try
4117                                 {
4118                                         s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(index));
4119                                         Assert.Fail ("#1");
4120                                 }
4121                                 catch
4122                                 {}
4123                                 try
4124                                 {
4125                                         s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, index));
4126                                         Assert.Fail ("#2");
4127                                 }
4128                                 catch
4129                                 {}
4130                         }
4131                 }
4132
4133                 [Test]
4134                 public void Shutdown_NoConnect ()
4135                 {
4136                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4137                         s.Bind (new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ()));
4138                         s.Listen (1);
4139                         try {
4140                                 s.Shutdown (SocketShutdown.Both);
4141                                 Assert.Fail ("#1");
4142                         } catch (SocketException exc) {
4143                                 Assert.AreEqual (10057, exc.ErrorCode, "#2");
4144                         } finally {
4145                                 s.Close ();
4146                         }
4147                 }
4148
4149                 [Test]
4150                 [ExpectedException (typeof (NullReferenceException))]
4151                 public void ReceiveAsync_Null ()
4152                 {
4153                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4154                                 s.ReceiveAsync (null);
4155                         }
4156                 }
4157
4158                 [Test]
4159                 [ExpectedException (typeof (NullReferenceException))]
4160                 public void ReceiveAsync_Default ()
4161                 {
4162                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4163                                 SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
4164                                 s.ReceiveAsync (saea);
4165                         }
4166                 }
4167
4168
4169                 [Test]
4170                 [ExpectedException (typeof (NullReferenceException))]
4171                 public void ReceiveAsync_NullBuffer ()
4172                 {
4173                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4174                                 SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
4175                                 saea.SetBuffer (null, 0, 0);
4176                                 s.ReceiveAsync (null);
4177                         }
4178                 }
4179
4180                 [Test]
4181                 [ExpectedException (typeof (ObjectDisposedException))]
4182                 public void ReceiveAsync_ClosedSocket ()
4183                 {
4184                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4185                         s.Close ();
4186                         s.ReceiveAsync (null);
4187                 }
4188
4189                 [Test]
4190                 [ExpectedException (typeof (NullReferenceException))]
4191                 public void SendAsync_Null ()
4192                 {
4193                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4194                                 s.SendAsync (null);
4195                         }
4196                 }
4197
4198                 [Test]
4199                 [ExpectedException (typeof (NullReferenceException))]
4200                 public void SendAsync_Default ()
4201                 {
4202                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4203                                 SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
4204                                 s.SendAsync (saea);
4205                         }
4206                 }
4207
4208
4209                 [Test]
4210                 [ExpectedException (typeof (NullReferenceException))]
4211                 public void SendAsync_NullBuffer ()
4212                 {
4213                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4214                                 SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
4215                                 saea.SetBuffer (null, 0, 0);
4216                                 s.SendAsync (null);
4217                         }
4218                 }
4219
4220                 [Test]
4221                 [ExpectedException (typeof (ObjectDisposedException))]
4222                 public void SendAsync_ClosedSocket ()
4223                 {
4224                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4225                         s.Close ();
4226                         s.SendAsync (null);
4227                 }
4228                 
4229                 [Test]
4230                 public void SendAsyncFile ()
4231                 {
4232                         Socket serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4233
4234                         serverSocket.Bind (new IPEndPoint (IPAddress.Loopback, 0));
4235                         serverSocket.Listen (1);
4236
4237                         var mReceived = new ManualResetEvent (false);
4238
4239                         serverSocket.BeginAccept (AsyncCall => {
4240                                 byte[] bytes = new byte [1024];
4241
4242                                 Socket listener = (Socket)AsyncCall.AsyncState;
4243                                 Socket client = listener.EndAccept (AsyncCall);
4244                                 client.Receive (bytes, bytes.Length, 0);
4245                                 client.Close ();
4246                                 mReceived.Set ();
4247                         }, serverSocket);
4248                         
4249                         Socket clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4250                         clientSocket.Connect (serverSocket.LocalEndPoint);
4251                         clientSocket.NoDelay = true;
4252                                                 
4253                         // Initialize buffer used to create testing file
4254                         var buffer = new byte [1024];
4255                         for (int i = 0; i < 1024; ++i)
4256                                 buffer [i] = (byte) (i % 256);
4257                         
4258                         string temp = Path.GetTempFileName ();
4259                         try {
4260                                 // Testing file creation
4261                                 using (StreamWriter sw = new StreamWriter (temp)) {
4262                                         sw.Write (buffer);
4263                                 }
4264
4265                                 var mSent = new ManualResetEvent (false);
4266
4267                                 // Async Send File to server
4268                                 clientSocket.BeginSendFile(temp, (ar) => {
4269                                         Socket client = (Socket) ar.AsyncState;
4270                                         client.EndSendFile (ar);
4271                                         mSent.Set ();
4272                                 }, clientSocket);
4273
4274                                 if (!mSent.WaitOne (1500))
4275                                         throw new TimeoutException ();
4276                                 if (!mReceived.WaitOne (1500))
4277                                         throw new TimeoutException ();
4278                         } finally {
4279                                 if (File.Exists (temp))
4280                                         File.Delete (temp);
4281                                         
4282                                 clientSocket.Close ();
4283                                 serverSocket.Close ();
4284                         }
4285                 }
4286                 
4287                 [Test]
4288                 public void ConnectToIPV4EndPointUsingDualModelSocket () {
4289                         using (var server = new Socket (SocketType.Stream, ProtocolType.Tcp))
4290                         using (var client = new Socket (SocketType.Stream, ProtocolType.Tcp)) {
4291                                 var host = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
4292                                         
4293                                 server.Bind (host);
4294                                 server.Listen (0);
4295                                 
4296                                 var ep = server.LocalEndPoint as IPEndPoint;
4297                                 
4298                                 client.Connect (ep);
4299                                 client.Disconnect (true);
4300                                 
4301                                 client.Connect (IPAddress.Loopback, ep.Port);
4302                                 client.Disconnect (true);
4303                                 
4304                                 client.Connect (new [] {IPAddress.Loopback}, ep.Port);
4305                                 client.Disconnect (true);
4306                         }
4307                 }
4308                 
4309                 [Test]
4310                 public void BeginConnectToIPV4EndPointUsingDualModelSocket () {
4311                         using (var server = new Socket (SocketType.Stream, ProtocolType.Tcp))
4312                         using (var client = new Socket (SocketType.Stream, ProtocolType.Tcp)) {
4313                                 var host = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
4314                                         
4315                                 server.Bind (host);
4316                                 server.Listen (0);
4317                                 
4318                                 var ep = server.LocalEndPoint as IPEndPoint;
4319                                 
4320                                 BCCalledBack.Reset ();
4321                                 var ar1 = client.BeginConnect (ep, BCCallback, client);
4322                                 Assert.IsTrue (BCCalledBack.WaitOne (10000), "#1");
4323                                 client.Disconnect (true);
4324                                 
4325                                 BCCalledBack.Reset ();
4326                                 var ar2 = client.BeginConnect (IPAddress.Loopback, ep.Port, BCCallback, client);
4327                                 Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2");
4328                                 client.Disconnect (true);
4329                                 
4330                                 BCCalledBack.Reset ();
4331                                 var ar3 = client.BeginConnect (new [] {IPAddress.Loopback}, ep.Port, BCCallback, client);
4332                                 Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2");
4333                                 client.Disconnect (true);
4334                         }
4335                 }
4336
4337                 [Test]
4338                 public void UdpMulticasTimeToLive ()
4339                 {
4340                         /* see https://bugzilla.xamarin.com/show_bug.cgi?id=36941 */
4341
4342                         using (Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
4343                                 IPEndPoint end_point = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
4344                                 socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
4345                                 socket.Bind (end_point);
4346                                 socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 19);
4347                         }
4348                 }
4349
4350                 [Test] // Covers 41616
4351                 public void ConnectAsyncUnhandledEx ()
4352                 {
4353                         var mre = new ManualResetEvent (false);
4354
4355                         var endPoint = new IPEndPoint(0,0);
4356                         var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Unspecified);
4357
4358                         var socketArgs = new SocketAsyncEventArgs();
4359                         socketArgs.RemoteEndPoint = endPoint;
4360                         socketArgs.Completed += (sender, e) => mre.Set ();
4361
4362                         socket.ConnectAsync (socketArgs);
4363
4364                         Assert.IsTrue (mre.WaitOne (1000), "ConnectedAsync timeout");
4365                 }
4366         }
4367 }
4368