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