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