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