[System] Get rid of useless catch-all clauses in SocketTest
[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.Net;
19 using System.Net.Sockets;
20 using NUnit.Framework;
21 using System.IO;
22
23 using System.Collections.Generic;
24
25 using MonoTests.Helpers;
26
27 namespace MonoTests.System.Net.Sockets
28 {
29         [TestFixture]
30         public class SocketTest
31         {
32                 // note: also used in SocketCas tests
33                 public const string BogusAddress = "192.168.244.244";
34                 public const int BogusPort = 23483;
35
36                 [Test]
37                 public void ConnectIPAddressAny ()
38                 {
39                         IPEndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
40
41                         /* UDP sockets use Any to disconnect
42                         try {
43                                 using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
44                                         s.Connect (ep);
45                                         s.Close ();
46                                 }
47                                 Assert.Fail ("#1");
48                         } catch (SocketException ex) {
49                                 Assert.AreEqual (10049, ex.ErrorCode, "#2");
50                         }
51                         */
52
53                         try {
54                                 using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
55                                         s.Connect (ep);
56                                         s.Close ();
57                                 }
58                                 Assert.Fail ("#3");
59                         } catch (SocketException ex) {
60                                 Assert.AreEqual (10049, ex.ErrorCode, "#4");
61                         }
62                 }
63
64                 [Test]
65                 [Ignore ("Bug #75158")] // Looks like MS fails after the .ctor, when you try to use the socket
66                 public void IncompatibleAddress ()
67                 {
68                         IPEndPoint epIPv6 = new IPEndPoint (IPAddress.IPv6Any,
69                                                                 NetworkHelpers.FindFreePort ());
70
71                         try {
72                                 using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)) {
73                                         s.Connect (epIPv6);
74                                         s.Close ();
75                                 }
76                                 Assert.Fail ("#1");
77                         } catch (SocketException ex) {
78                                 // address incompatible with protocol
79                                 int expectedError = 10047;
80                                 Assert.AreEqual (expectedError, ex.ErrorCode,
81                                                 "#2");
82                         }
83                 }
84
85                 [Test]
86                 [Category ("InetAccess")]
87                 public void BogusEndConnect ()
88                 {
89                         IPAddress ipOne = IPAddress.Parse (BogusAddress);
90                         IPEndPoint ipEP = new IPEndPoint (ipOne, BogusPort);
91                         Socket sock = new Socket (ipEP.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
92                         IAsyncResult ar = sock.BeginConnect (ipEP, null, null);
93
94                         try {
95                                 // should raise an exception because connect was bogus
96                                 sock.EndConnect (ar);
97                                 Assert.Fail ("#1");
98                         } catch (SocketException ex) {
99                                 // Actual error code depends on network configuration.
100                                 var error = (SocketError) ex.ErrorCode;
101                                 Assert.That (error == SocketError.TimedOut ||
102                                              error == SocketError.ConnectionRefused ||
103                                              error == SocketError.NetworkUnreachable ||
104                                              error == SocketError.HostUnreachable, "#2");
105                         }
106                 }
107
108                 [Test]
109                 [ExpectedException (typeof (ArgumentNullException))]
110                 public void SelectEmpty ()
111                 {
112                         ArrayList list = new ArrayList ();
113                         Socket.Select (list, list, list, 1000);
114                 }
115                 
116                 private bool BlockingConnect (bool block, int port)
117                 {
118                         IPEndPoint ep = new IPEndPoint(IPAddress.Loopback, port);
119                         Socket server = new Socket(AddressFamily.InterNetwork,
120                                                    SocketType.Stream,
121                                                    ProtocolType.Tcp);
122                         server.Bind(ep);
123                         server.Blocking=block;
124
125                         server.Listen(0);
126
127                         Socket conn = new Socket (AddressFamily.InterNetwork,
128                                                   SocketType.Stream,
129                                                   ProtocolType.Tcp);
130                         conn.Connect (ep);
131
132                         Socket client = null;
133                         var sw = Stopwatch.StartNew ();
134                         while (sw.ElapsedMilliseconds < 100)
135                         {
136                                 try {
137                                         client = server.Accept();
138                                         break;
139                                 }
140                                 catch (SocketException ex) {
141                                         if (ex.SocketErrorCode == SocketError.WouldBlock)
142                                                 continue;
143                                         throw;
144                                 }
145                         }
146                         Assert.IsNotNull (client, "Couldn't accept a client connection within 100ms.");
147                         bool client_block = client.Blocking;
148
149                         client.Close();
150                         conn.Close();
151                         server.Close();
152                         
153                         return(client_block);
154                 }
155
156                 [Test]
157                 public void AcceptBlockingStatus()
158                 {
159                         bool block;
160                         var port = NetworkHelpers.FindFreePort ();
161         
162                         block = BlockingConnect(true, port);
163                         Assert.AreEqual (block, true, "BlockingStatus01");
164
165                         block = BlockingConnect(false, port);
166                         Assert.AreEqual (block, false, "BlockingStatus02");
167                 }
168
169                 static bool CFAConnected = false;
170                 static ManualResetEvent CFACalledBack;
171                 
172                 private static void CFACallback (IAsyncResult asyncResult)
173                 {
174                         Socket sock = (Socket)asyncResult.AsyncState;
175                         CFAConnected = sock.Connected;
176                         
177                         if (sock.Connected) {
178                                 sock.EndConnect (asyncResult);
179                         }
180
181                         CFACalledBack.Set ();
182                 }
183
184                 [Test] // Connect (IPEndPoint)
185                 public void Connect1_RemoteEP_Null ()
186                 {
187                         Socket s = new Socket (AddressFamily.InterNetwork,
188                                 SocketType.Stream, ProtocolType.Tcp);
189                         try {
190                                 s.Connect ((IPEndPoint) null);
191                                 Assert.Fail ("#1");
192                         } catch (ArgumentNullException ex) {
193                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
194                                 Assert.IsNull (ex.InnerException, "#3");
195                                 Assert.IsNotNull (ex.Message, "#4");
196                                 Assert.AreEqual ("remoteEP", ex.ParamName, "#5");
197                         }
198                 }
199
200                 [Test]
201                 public void ConnectFailAsync ()
202                 {
203                         Socket sock = new Socket (AddressFamily.InterNetwork,
204                                                   SocketType.Stream,
205                                                   ProtocolType.Tcp);
206                         sock.Blocking = false;
207                         CFACalledBack = new ManualResetEvent (false);
208                         CFACalledBack.Reset ();
209
210                         /* Need a port that is not being used for
211                          * anything...
212                          */
213                         sock.BeginConnect (new IPEndPoint (IPAddress.Loopback,
214                                                            NetworkHelpers.FindFreePort ()),
215                                            new AsyncCallback (CFACallback),
216                                            sock);
217                         CFACalledBack.WaitOne ();
218
219                         Assert.AreEqual (CFAConnected, false, "ConnectFail");
220                 }
221                 
222                 [Test]
223                 public void SetSocketOptionBoolean ()
224                 {
225                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
226                         Socket sock = new Socket (ep.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
227                         try {
228                                 sock.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
229                         } finally {
230                                 sock.Close ();
231                         }
232                 }
233                 [Test]
234                 public void TestSelect1 ()
235                 {
236                         Socket srv = CreateServer (NetworkHelpers.FindFreePort ());
237                         ClientSocket clnt = new ClientSocket (srv.LocalEndPoint);
238                         Thread th = new Thread (new ThreadStart (clnt.ConnectSleepClose));
239                         Socket acc = null;
240                         try {
241                                 th.Start ();
242                                 acc = srv.Accept ();
243                                 clnt.Write ();
244                                 ArrayList list = new ArrayList ();
245                                 ArrayList empty = new ArrayList ();
246                                 list.Add (acc);
247                                 Socket.Select (list, empty, empty, 100);
248                                 Assert.AreEqual (0, empty.Count, "#01");
249                                 Assert.AreEqual (1, list.Count, "#02");
250                                 Socket.Select (empty, list, empty, 100);
251                                 Assert.AreEqual (0, empty.Count, "#03");
252                                 Assert.AreEqual (1, list.Count, "#04");
253                                 Socket.Select (list, empty, empty, -1);
254                                 Assert.AreEqual (0, empty.Count, "#05");
255                                 Assert.AreEqual (1, list.Count, "#06");
256                                 // Need to read the 10 bytes from the client to avoid a RST
257                                 byte [] bytes = new byte [10];
258                                 acc.Receive (bytes);
259                         } finally {
260                                 if (acc != null)
261                                         acc.Close ();
262                                 srv.Close ();
263                         }
264                 }
265
266                 static Socket CreateServer (int port)
267                 {
268                         Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
269                         sock.Bind (new IPEndPoint (IPAddress.Loopback, port));
270                         sock.Listen (1);
271                         return sock;
272                 }
273
274                 class ClientSocket {
275                         Socket sock;
276                         EndPoint ep;
277
278                         public ClientSocket (EndPoint ep)
279                         {
280                                 this.ep = ep;
281                                 sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
282                         }
283
284                         public void ConnectSleepClose ()
285                         {
286                                 sock.Connect (ep);
287                                 Thread.Sleep (2000);
288                                 sock.Close ();
289                         }
290
291                         public void Write ()
292                         {
293                                 byte [] b = new byte [10];
294                                 sock.Send (b);
295                         }
296                 }
297
298                 byte[] buf = new byte[100];
299
300                 [Test]
301                 [ExpectedException (typeof (ObjectDisposedException))]
302                 public void Disposed2 ()
303                 {
304                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
305                         s.Close();
306
307                         s.Blocking = true;
308                 }
309
310                 [Test]
311                 [ExpectedException (typeof (ObjectDisposedException))]
312                 public void Disposed6 ()
313                 {
314                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
315                         s.Close();
316
317                         s.Listen (5);
318                 }
319
320                 [Test]
321                 [ExpectedException (typeof (ObjectDisposedException))]
322                 public void Disposed7 ()
323                 {
324                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
325                         s.Close();
326
327                         s.Poll (100, 0);
328                 }
329
330                 [Test]
331                 [ExpectedException (typeof (ObjectDisposedException))]
332                 public void Disposed15 ()
333                 {
334                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
335                         s.Close();
336
337                         s.Send (buf);
338                 }
339
340                 [Test]
341                 [ExpectedException (typeof (ObjectDisposedException))]
342                 public void Disposed16 ()
343                 {
344                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
345                         s.Close();
346
347                         s.Send (buf, 0);
348                 }
349
350                 [Test]
351                 [ExpectedException (typeof (ObjectDisposedException))]
352                 public void Disposed17 ()
353                 {
354                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
355                         s.Close();
356
357                         s.Send (buf, 10, 0);
358                 }
359
360                 [Test]
361                 [ExpectedException (typeof (ObjectDisposedException))]
362                 public void Disposed18 ()
363                 {
364                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
365                         s.Close();
366
367                         s.Send (buf, 0, 10, 0);
368                 }
369
370                 [Test]
371                 [ExpectedException (typeof (ObjectDisposedException))]
372                 public void Disposed19 ()
373                 {
374                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
375                         EndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
376                         s.Close();
377
378                         s.SendTo (buf, 0, ep);
379                 }
380
381                 [Test]
382                 [ExpectedException (typeof (ObjectDisposedException))]
383                 public void Disposed20 ()
384                 {
385                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
386                         EndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
387                         s.Close();
388
389                         s.SendTo (buf, 10, 0, ep);
390                 }
391
392                 [Test]
393                 [ExpectedException (typeof (ObjectDisposedException))]
394                 public void Disposed21 ()
395                 {
396                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
397                         EndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
398                         s.Close();
399
400                         s.SendTo (buf, 0, 10, 0, ep);
401                 }
402
403                 [Test]
404                 [ExpectedException (typeof (ObjectDisposedException))]
405                 public void Disposed22 ()
406                 {
407                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
408                         EndPoint ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
409                         s.Close();
410
411                         s.SendTo (buf, ep);
412                 }
413
414                 [Test]
415                 [ExpectedException (typeof (ObjectDisposedException))]
416                 public void Disposed23 ()
417                 {
418                         Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
419                         s.Close();
420
421                         s.Shutdown (0);
422                 }
423
424                 [Test]
425                 public void GetHashCodeTest ()
426                 {
427                         Socket server = new Socket (AddressFamily.InterNetwork,
428                                 SocketType.Stream, ProtocolType.Tcp);
429                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
430                                                         NetworkHelpers.FindFreePort ());
431                         server.Bind (ep);
432                         server.Listen (1);
433
434                         Socket client = new Socket (AddressFamily.InterNetwork, 
435                                 SocketType.Stream, ProtocolType.Tcp);
436                         int hashcodeA = client.GetHashCode ();
437                         client.Connect (ep);
438                         int hashcodeB = client.GetHashCode ();
439                         Assert.AreEqual (hashcodeA, hashcodeB, "#1");
440                         client.Close ();
441                         int hashcodeC = client.GetHashCode ();
442                         Assert.AreEqual (hashcodeB, hashcodeC, "#2");
443                         server.Close ();
444                 }
445
446                 static ManualResetEvent SocketError_event = new ManualResetEvent (false);
447
448                 private static void SocketError_callback (IAsyncResult ar)
449                 {
450                         Socket sock = (Socket)ar.AsyncState;
451                         
452                         if(sock.Connected) {
453                                 sock.EndConnect (ar);
454                         }
455
456                         SocketError_event.Set ();
457                 }
458
459                 [Test]
460                 public void SocketErrorTest ()
461                 {
462                         Socket sock = new Socket (AddressFamily.InterNetwork,
463                                                   SocketType.Stream,
464                                                   ProtocolType.Tcp);
465                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
466                                                         BogusPort);
467                         
468                         SocketError_event.Reset ();
469
470                         sock.Blocking = false;
471                         sock.BeginConnect (ep, new AsyncCallback(SocketError_callback),
472                                 sock);
473
474                         if (SocketError_event.WaitOne (2000, false) == false) {
475                                 Assert.Fail ("SocketError wait timed out");
476                         }
477
478                         Assert.AreEqual (false, sock.Connected, "SocketError #1");
479
480                         int error;
481
482                         error = (int)sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
483                         Assert.AreEqual (10061, error, "SocketError #2");
484
485                         error = (int)sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
486                         Assert.AreEqual (10061, error, "SocketError #3");
487
488                         sock.Close ();
489                 }
490                 
491
492                 [Test]
493                 public void SocketInformationCtor ()
494                 {
495                 }
496                 
497                 [Test]
498                 public void DontFragmentDefaultTcp ()
499                 {
500                         Socket sock = new Socket (AddressFamily.InterNetwork,
501                                                   SocketType.Stream,
502                                                   ProtocolType.Tcp);
503                         
504                         Assert.AreEqual (false, sock.DontFragment, "DontFragmentDefaultTcp");
505
506                         sock.Close ();
507                 }
508
509                 [Test]
510                 [Category ("NotWorking")] // DontFragment doesn't work
511                 public void DontFragmentChangeTcp ()
512                 {
513                         Socket sock = new Socket (AddressFamily.InterNetwork,
514                                                   SocketType.Stream,
515                                                   ProtocolType.Tcp);
516                         
517                         sock.DontFragment = true;
518                         
519                         Assert.AreEqual (true, sock.DontFragment, "DontFragmentChangeTcp");
520
521                         sock.Close ();
522                 }
523                 
524                 [Test]
525                 public void DontFragmentDefaultUdp ()
526                 {
527                         Socket sock = new Socket (AddressFamily.InterNetwork,
528                                                   SocketType.Dgram,
529                                                   ProtocolType.Udp);
530                         
531                         Assert.AreEqual (false, sock.DontFragment, "DontFragmentDefaultUdp");
532
533                         sock.Close ();
534                 }
535
536                 [Test]
537                 [Category ("NotWorking")] // DontFragment doesn't work
538                 public void DontFragmentChangeUdp ()
539                 {
540                         Socket sock = new Socket (AddressFamily.InterNetwork,
541                                                   SocketType.Dgram,
542                                                   ProtocolType.Udp);
543                         
544                         sock.DontFragment = true;
545                         
546                         Assert.AreEqual (true, sock.DontFragment, "DontFragmentChangeUdp");
547
548                         sock.Close ();
549                 }
550
551                 [Test]
552                 [ExpectedException (typeof(ObjectDisposedException))]
553                 public void DontFragmentClosed ()
554                 {
555                         Socket sock = new Socket (AddressFamily.InterNetwork,
556                                                   SocketType.Stream,
557                                                   ProtocolType.Tcp);
558                         
559                         sock.Close ();
560                         
561                         bool val = sock.DontFragment;
562                 }
563                 
564                 [Test]
565                 [Category ("NotWorking")] // Need to pick a non-IP AddressFamily that "works" on both mono and ms, this one only works on ms
566                 public void DontFragment ()
567                 {
568                         Socket sock = new Socket (AddressFamily.NetBios,
569                                                   SocketType.Seqpacket,
570                                                   ProtocolType.Unspecified);
571                         
572                         try {
573                                 sock.DontFragment = true;
574                                 Assert.Fail ("DontFragment #1");
575                         } catch (NotSupportedException) {
576                         } finally {
577                                 sock.Close ();
578                         }
579                 }
580                 
581                 [Test]
582                 public void EnableBroadcastDefaultTcp ()
583                 {
584                         Socket sock = new Socket (AddressFamily.InterNetwork,
585                                                   SocketType.Stream,
586                                                   ProtocolType.Tcp);
587                         
588                         try {
589                                 bool value = sock.EnableBroadcast;
590                                 Assert.Fail ("EnableBroadcastDefaultTcp #1");
591                         } catch (SocketException ex) {
592                                 Assert.AreEqual (10042, ex.ErrorCode, "EnableBroadcastDefaultTcp #2");
593                         } finally {
594                                 sock.Close ();
595                         }
596                 }
597
598                 [Test]
599                 public void EnableBroadcastDefaultUdp ()
600                 {
601                         Socket sock = new Socket (AddressFamily.InterNetwork,
602                                                   SocketType.Dgram,
603                                                   ProtocolType.Udp);
604                         
605                         Assert.AreEqual (false, sock.EnableBroadcast, "EnableBroadcastDefaultUdp");
606
607                         sock.Close ();
608                 }
609                 
610                 [Test]
611                 public void EnableBroadcastChangeTcp ()
612                 {
613                         Socket sock = new Socket (AddressFamily.InterNetwork,
614                                                   SocketType.Stream,
615                                                   ProtocolType.Tcp);
616                         
617                         try {
618                                 sock.EnableBroadcast = true;
619                                 Assert.Fail ("EnableBroadcastChangeTcp #1");
620                         } catch (SocketException ex) {
621                                 Assert.AreEqual (10042, ex.ErrorCode, "EnableBroadcastChangeTcp #2");
622                         } finally {
623                                 sock.Close ();
624                         }
625                 }
626                 
627                 [Test]
628                 public void EnableBroadcastChangeUdp ()
629                 {
630                         Socket sock = new Socket (AddressFamily.InterNetwork,
631                                                   SocketType.Dgram,
632                                                   ProtocolType.Udp);
633                         
634                         sock.EnableBroadcast = true;
635                         
636                         Assert.AreEqual (true, sock.EnableBroadcast, "EnableBroadcastChangeUdp");
637
638                         sock.Close ();
639                 }
640
641                 [Test]
642                 [ExpectedException (typeof(ObjectDisposedException))]
643                 public void EnableBroadcastClosed ()
644                 {
645                         Socket sock = new Socket (AddressFamily.InterNetwork,
646                                                   SocketType.Dgram,
647                                                   ProtocolType.Udp);
648                         
649                         sock.Close ();
650                         
651                         bool val = sock.EnableBroadcast;
652                 }
653
654                 /* Can't test the default for ExclusiveAddressUse as
655                  * it's different on different versions and service
656                  * packs of windows
657                  */
658                 [Test]
659                 [Category ("NotWorking")] // Not supported on Linux
660                 public void ExclusiveAddressUseUnbound ()
661                 {
662                         Socket sock = new Socket (AddressFamily.InterNetwork,
663                                                   SocketType.Stream,
664                                                   ProtocolType.Tcp);
665                         
666                         sock.ExclusiveAddressUse = true;
667                         
668                         Assert.AreEqual (true, sock.ExclusiveAddressUse, "ExclusiveAddressUseUnbound");
669                         
670                         sock.Close ();
671                 }
672
673                 [Test]
674                 [ExpectedException (typeof(InvalidOperationException))]
675                 [Category ("NotWorking")] // Not supported on Linux
676                 public void ExclusiveAddressUseBound ()
677                 {
678                         Socket sock = new Socket (AddressFamily.InterNetwork,
679                                                   SocketType.Stream,
680                                                   ProtocolType.Tcp);
681                         
682                         sock.Bind (new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ()));
683                         sock.ExclusiveAddressUse = true;
684                         sock.Close ();
685                 }
686
687                 [Test]
688                 [ExpectedException (typeof(ObjectDisposedException))]
689                 public void ExclusiveAddressUseClosed ()
690                 {
691                         Socket sock = new Socket (AddressFamily.InterNetwork,
692                                                   SocketType.Stream,
693                                                   ProtocolType.Tcp);
694                         
695                         sock.Close ();
696                         
697                         bool val = sock.ExclusiveAddressUse;
698                 }
699                 
700                 [Test]
701                 public void IsBoundTcp ()
702                 {
703                         Socket sock = new Socket (AddressFamily.InterNetwork,
704                                                   SocketType.Stream,
705                                                   ProtocolType.Tcp);
706                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
707                                                         BogusPort);
708                         
709                         Assert.AreEqual (false, sock.IsBound, "IsBoundTcp #1");
710                         
711                         sock.Bind (ep);
712                         Assert.AreEqual (true, sock.IsBound, "IsBoundTcp #2");
713
714                         sock.Listen (1);
715                         
716                         Socket sock2 = new Socket (AddressFamily.InterNetwork,
717                                                    SocketType.Stream,
718                                                    ProtocolType.Tcp);
719                         
720                         Assert.AreEqual (false, sock2.IsBound, "IsBoundTcp #3");
721                         
722                         sock2.Connect (ep);
723                         Assert.AreEqual (true, sock2.IsBound, "IsBoundTcp #4");
724                         
725                         sock2.Close ();
726                         Assert.AreEqual (true, sock2.IsBound, "IsBoundTcp #5");
727
728                         sock.Close ();
729                         Assert.AreEqual (true, sock.IsBound, "IsBoundTcp #6");
730                 }
731
732                 [Test]
733                 public void IsBoundUdp ()
734                 {
735                         Socket sock = new Socket (AddressFamily.InterNetwork,
736                                                   SocketType.Dgram,
737                                                   ProtocolType.Udp);
738                         IPEndPoint ep = new IPEndPoint (IPAddress.Loopback,
739                                                         BogusPort);
740                         
741                         Assert.AreEqual (false, sock.IsBound, "IsBoundUdp #1");
742                         
743                         sock.Bind (ep);
744                         Assert.AreEqual (true, sock.IsBound, "IsBoundUdp #2");
745                         
746                         sock.Close ();
747                         Assert.AreEqual (true, sock.IsBound, "IsBoundUdp #3");
748                         
749
750                         sock = new Socket (AddressFamily.InterNetwork,
751                                            SocketType.Dgram,
752                                            ProtocolType.Udp);
753                         
754                         Assert.AreEqual (false, sock.IsBound, "IsBoundUdp #4");
755                         
756                         sock.Connect (ep);
757                         Assert.AreEqual (true, sock.IsBound, "IsBoundUdp #5");
758                         
759                         sock.Close ();
760                         Assert.AreEqual (true, sock.IsBound, "IsBoundUdp #6");
761                 }
762
763                 [Test]
764                 /* Should not throw an exception */
765                 public void IsBoundClosed ()
766                 {
767                         Socket sock = new Socket (AddressFamily.InterNetwork,
768                                                   SocketType.Stream,
769                                                   ProtocolType.Tcp);
770                         
771                         sock.Close ();
772                         
773                         bool val = sock.IsBound;
774                 }
775                 
776                 /* Nothing much to test for LingerState */
777                 
778                 [Test]
779                 public void MulticastLoopbackDefaultTcp ()
780                 {
781                         Socket sock = new Socket (AddressFamily.InterNetwork,
782                                                   SocketType.Stream,
783                                                   ProtocolType.Tcp);
784                         
785                         try {
786                                 bool value = sock.MulticastLoopback;
787                                 Assert.Fail ("MulticastLoopbackDefaultTcp #1");
788                         } catch (SocketException ex) {
789                                 Assert.AreEqual (10042, ex.ErrorCode, "MulticastLoopbackDefaultTcp #2");
790                         } finally {
791                                 sock.Close ();
792                         }
793                 }
794
795                 [Test]
796                 public void MulticastLoopbackChangeTcp ()
797                 {
798                         Socket sock = new Socket (AddressFamily.InterNetwork,
799                                                   SocketType.Stream,
800                                                   ProtocolType.Tcp);
801                         
802                         try {
803                                 sock.MulticastLoopback = false;
804                                 Assert.Fail ("MulticastLoopbackChangeTcp #1");
805                         } catch (SocketException ex) {
806                                 Assert.AreEqual (10042, ex.ErrorCode, "MulticastLoopbackChangeTcp #2");
807                         } finally {
808                                 sock.Close ();
809                         }
810                 }
811                 
812                 [Test]
813                 public void MulticastLoopbackDefaultUdp ()
814                 {
815                         Socket sock = new Socket (AddressFamily.InterNetwork,
816                                                   SocketType.Dgram,
817                                                   ProtocolType.Udp);
818                         
819                         Assert.AreEqual (true, sock.MulticastLoopback, "MulticastLoopbackDefaultUdp");
820                         
821                         sock.Close ();
822                 }
823                 
824                 [Test]
825                 public void MulticastLoopbackChangeUdp ()
826                 {
827                         Socket sock = new Socket (AddressFamily.InterNetwork,
828                                                   SocketType.Dgram,
829                                                   ProtocolType.Udp);
830                         
831                         sock.MulticastLoopback = false;
832                         
833                         Assert.AreEqual (false, sock.MulticastLoopback, "MulticastLoopbackChangeUdp");
834                         
835                         sock.Close ();
836                 }
837
838                 [Test]
839                 [ExpectedException (typeof(ObjectDisposedException))]
840                 public void MulticastLoopbackClosed ()
841                 {
842                         Socket sock = new Socket (AddressFamily.InterNetwork,
843                                                   SocketType.Stream,
844                                                   ProtocolType.Tcp);
845                         
846                         sock.Close ();
847                         
848                         bool val = sock.MulticastLoopback;
849                 }
850                 
851                 /* OSSupportsIPv6 depends on the environment */
852                 
853                 [Test]
854                 [Category("NotWorking")] // We have different defaults for perf reasons
855                 public void ReceiveBufferSizeDefault ()
856                 {
857                         Socket sock = new Socket (AddressFamily.InterNetwork,
858                                                   SocketType.Stream,
859                                                   ProtocolType.Tcp);
860                         
861                         Assert.AreEqual (8192, sock.ReceiveBufferSize, "ReceiveBufferSizeDefault");
862                         
863                         sock.Close ();
864                 }
865                 
866                 [Test]
867                 [Category("NotWorking")] // We have different defaults for perf reasons
868                 public void ReceiveBufferSizeDefaultUdp ()
869                 {
870                         Socket sock = new Socket (AddressFamily.InterNetwork,
871                                                   SocketType.Dgram,
872                                                   ProtocolType.Udp);
873                         
874                         Assert.AreEqual (8192, sock.ReceiveBufferSize, "ReceiveBufferSizeDefaultUdp");
875                         
876                         sock.Close ();
877                 }
878
879                 [Test]
880                 public void ReceiveBufferSizeChange ()
881                 {
882                         Socket sock = new Socket (AddressFamily.InterNetwork,
883                                                   SocketType.Stream,
884                                                   ProtocolType.Tcp);
885                         
886                         sock.ReceiveBufferSize = 16384;
887                         
888                         Assert.AreEqual (16384, sock.ReceiveBufferSize, "ReceiveBufferSizeChange");
889                         
890                         sock.Close ();
891                 }
892
893                 [Test]
894                 [Category("NotWorking")] // We cannot totally remove buffers (minimum is set to 256
895                 public void BuffersCheck_None ()
896                 {
897                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
898                                 int original = s.ReceiveBufferSize;
899                                 s.ReceiveBufferSize = 0;
900                                 Assert.AreEqual (0, s.ReceiveBufferSize, "ReceiveBufferSize " + original.ToString ());
901
902                                 original = s.SendBufferSize;
903                                 s.SendBufferSize = 0;
904                                 Assert.AreEqual (0, s.SendBufferSize, "SendBufferSize " + original.ToString ());
905                         }
906                 }
907
908                 [Test]
909                 [ExpectedException (typeof(ObjectDisposedException))]
910                 public void ReceiveBufferSizeClosed ()
911                 {
912                         Socket sock = new Socket (AddressFamily.InterNetwork,
913                                                   SocketType.Stream,
914                                                   ProtocolType.Tcp);
915                         
916                         sock.Close ();
917                         
918                         int val = sock.ReceiveBufferSize;
919                 }
920                 
921                 [Test]
922                 [Category("NotWorking")] // We have different defaults for perf reasons
923                 public void SendBufferSizeDefault ()
924                 {
925                         Socket sock = new Socket (AddressFamily.InterNetwork,
926                                                   SocketType.Stream,
927                                                   ProtocolType.Tcp);
928                         
929                         Assert.AreEqual (8192, sock.SendBufferSize, "SendBufferSizeDefault");
930                         
931                         sock.Close ();
932                 }
933                 
934                 [Test]
935                 [Category("NotWorking")] // We have different defaults for perf reasons
936                 public void SendBufferSizeDefaultUdp ()
937                 {
938                         Socket sock = new Socket (AddressFamily.InterNetwork,
939                                                   SocketType.Dgram,
940                                                   ProtocolType.Udp);
941                         
942                         Assert.AreEqual (8192, sock.SendBufferSize, "SendBufferSizeDefaultUdp");
943                         
944                         sock.Close ();
945                 }
946
947                 [Test]
948                 public void SendBufferSizeChange ()
949                 {
950                         Socket sock = new Socket (AddressFamily.InterNetwork,
951                                                   SocketType.Stream,
952                                                   ProtocolType.Tcp);
953                         
954                         sock.SendBufferSize = 16384;
955                         
956                         Assert.AreEqual (16384, sock.SendBufferSize, "SendBufferSizeChange");
957                         
958                         sock.Close ();
959                 }
960
961                 [Test]
962                 [ExpectedException (typeof(ObjectDisposedException))]
963                 public void SendBufferSizeClosed ()
964                 {
965                         Socket sock = new Socket (AddressFamily.InterNetwork,
966                                                   SocketType.Stream,
967                                                   ProtocolType.Tcp);
968                         
969                         sock.Close ();
970                         
971                         int val = sock.SendBufferSize;
972                 }
973                 
974                 /* No test for TTL default as it's platform dependent */
975                 [Test]
976                 public void TtlChange ()
977                 {
978                         Socket sock = new Socket (AddressFamily.InterNetwork,
979                                                   SocketType.Stream,
980                                                   ProtocolType.Tcp);
981                         
982                         sock.Ttl = 255;
983                         
984                         Assert.AreEqual (255, sock.Ttl, "TtlChange");
985                         
986                         sock.Close ();
987                 }
988
989                 [Test]
990                 [Category ("NotOnMac")] // Mac doesn't throw when overflowing the ttl
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 (SocketException ex) {
1001                                 Assert.AreEqual (10022, ex.ErrorCode,
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 = StartSocketServer ();
4233                         
4234                         Socket clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4235                         clientSocket.Connect (serverSocket.LocalEndPoint);
4236                         clientSocket.NoDelay = true;
4237                                                 
4238                         // Initialize buffer used to create testing file
4239                         var buffer = new byte [1024];
4240                         for (int i = 0; i < 1024; ++i)
4241                                 buffer [i] = (byte) (i % 256);
4242                         
4243                         string temp = Path.GetTempFileName ();
4244                         try {
4245                                 // Testing file creation
4246                                 using (StreamWriter sw = new StreamWriter (temp)) {
4247                                         sw.Write (buffer);
4248                                 }
4249
4250                                 var m = new ManualResetEvent (false);
4251
4252                                 // Async Send File to server
4253                                 clientSocket.BeginSendFile(temp, (ar) => {
4254                                         Socket client = (Socket) ar.AsyncState;
4255                                         client.EndSendFile (ar);
4256                                         m.Set ();
4257                                 }, clientSocket);
4258
4259                                 if (!m.WaitOne (1500))
4260                                         throw new TimeoutException ();
4261                                 m.Reset ();
4262                         } finally {
4263                                 if (File.Exists (temp))
4264                                         File.Delete (temp);
4265                                         
4266                                 clientSocket.Close ();
4267                                 serverSocket.Close ();
4268                         }
4269                 }
4270                 
4271                 [Test]
4272                 public void ConnectToIPV4EndPointUsingDualModelSocket () {
4273                         using (var server = new Socket (SocketType.Stream, ProtocolType.Tcp))
4274                         using (var client = new Socket (SocketType.Stream, ProtocolType.Tcp)) {
4275                                 var host = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
4276                                         
4277                                 server.Bind (host);
4278                                 server.Listen (0);
4279                                 
4280                                 var ep = server.LocalEndPoint as IPEndPoint;
4281                                 
4282                                 client.Connect (ep);
4283                                 client.Disconnect (true);
4284                                 
4285                                 client.Connect (IPAddress.Loopback, ep.Port);
4286                                 client.Disconnect (true);
4287                                 
4288                                 client.Connect (new [] {IPAddress.Loopback}, ep.Port);
4289                                 client.Disconnect (true);
4290                         }
4291                 }
4292                 
4293                 [Test]
4294                 public void BeginConnectToIPV4EndPointUsingDualModelSocket () {
4295                         using (var server = new Socket (SocketType.Stream, ProtocolType.Tcp))
4296                         using (var client = new Socket (SocketType.Stream, ProtocolType.Tcp)) {
4297                                 var host = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
4298                                         
4299                                 server.Bind (host);
4300                                 server.Listen (0);
4301                                 
4302                                 var ep = server.LocalEndPoint as IPEndPoint;
4303                                 
4304                                 BCCalledBack.Reset ();
4305                                 var ar1 = client.BeginConnect (ep, BCCallback, client);
4306                                 Assert.IsTrue (BCCalledBack.WaitOne (10000), "#1");
4307                                 client.Disconnect (true);
4308                                 
4309                                 BCCalledBack.Reset ();
4310                                 var ar2 = client.BeginConnect (IPAddress.Loopback, ep.Port, BCCallback, client);
4311                                 Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2");
4312                                 client.Disconnect (true);
4313                                 
4314                                 BCCalledBack.Reset ();
4315                                 var ar3 = client.BeginConnect (new [] {IPAddress.Loopback}, ep.Port, BCCallback, client);
4316                                 Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2");
4317                                 client.Disconnect (true);
4318                         }
4319                 }
4320
4321                 Socket StartSocketServer ()
4322                 {
4323
4324                         Socket listenSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4325                         
4326                         listenSocket.Bind (new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ()));
4327                         listenSocket.Listen (1);
4328
4329                         listenSocket.BeginAccept (new AsyncCallback (ReceiveCallback), listenSocket);
4330                         
4331                         return listenSocket;
4332                 }
4333
4334                 public static void ReceiveCallback (IAsyncResult AsyncCall)
4335                 {
4336                         byte[] bytes = new byte [1024];
4337
4338                         Socket listener = (Socket)AsyncCall.AsyncState;
4339                         Socket client = listener.EndAccept (AsyncCall);
4340  
4341                         client.Receive (bytes, bytes.Length, 0);
4342                         client.Close ();
4343                 }
4344
4345                 [Test]
4346                 public void UdpMulticasTimeToLive ()
4347                 {
4348                         /* see https://bugzilla.xamarin.com/show_bug.cgi?id=36941 */
4349
4350                         using (Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
4351                                 IPEndPoint end_point = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
4352                                 socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
4353                                 socket.Bind (end_point);
4354                                 socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 19);
4355                         }
4356                 }
4357         }
4358 }
4359