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