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