[socket] Add EPROTOTYPE error case (#4391)
[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 #if FEATURE_NO_BSD_SOCKETS
2721                 [ExpectedException (typeof (AggregateException))] // Something catches the PlatformNotSupportedException and re-throws an AggregateException    
2722 #endif
2723                 public void ConcurrentExceedSocketLimit ()
2724                 {
2725                         var tasks = new Task[4];
2726                         for (int i = 0; i < 4; i++) {
2727                                 tasks[i] = Task.Factory.StartNew (() => SendGenericExceedBuffer ());
2728                         }
2729                         Task.WaitAll (tasks);
2730                 }
2731
2732                 [Test]
2733 #if FEATURE_NO_BSD_SOCKETS
2734                 [ExpectedException (typeof (PlatformNotSupportedException))]
2735 #endif
2736                 public void SendGenericExceedBuffer ()
2737                 {
2738                         // Create a buffer larger than the default max.
2739                         const int BUFFER_SIZE = 65 * 1024;
2740                         int i;
2741
2742                         IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, NetworkHelpers.FindFreePort ());
2743
2744                         Socket listensock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
2745                         listensock.Bind (endpoint);
2746                         listensock.Listen (1);
2747
2748                         Socket sendsock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
2749                         sendsock.Connect (endpoint);
2750
2751                         Socket clientsock = listensock.Accept ();
2752
2753                         byte[] sendbuf = new byte[BUFFER_SIZE];
2754
2755                         for (i = 0; i < BUFFER_SIZE; i++) {
2756                                 sendbuf[i] = (byte)i;
2757                         }
2758
2759                         Task sendTask = Task.Factory.StartNew(() => {
2760                                 int sent = sendsock.Send (sendbuf);
2761
2762                                 Assert.AreEqual (BUFFER_SIZE, sent, "#1");
2763                         });
2764
2765                         byte[] recvbuf = new byte[BUFFER_SIZE];
2766
2767                         Task recvTask = Task.Factory.StartNew(() => {
2768                                 int totalReceived = 0;
2769                                 byte[] buffer = new byte[256];
2770                                 while (totalReceived < sendbuf.Length) {
2771                                         int recvd = clientsock.Receive (buffer, 0, buffer.Length, SocketFlags.None);
2772                                         Array.Copy (buffer, 0, recvbuf, totalReceived, recvd);
2773                                         totalReceived += recvd;
2774                                 }
2775
2776                                 Assert.AreEqual (BUFFER_SIZE, totalReceived, "#2");
2777                         });
2778
2779                         Assert.IsTrue (Task.WaitAll (new []{sendTask, recvTask}, 20 * 1000), "#2a");
2780
2781                         for (i = 0; i < BUFFER_SIZE; i++) {
2782                                 Assert.AreEqual (recvbuf[i], sendbuf[i],
2783                                                  "#3/" + i.ToString());
2784                         }
2785
2786                         sendsock.Close ();
2787                         clientsock.Close ();
2788                         listensock.Close ();
2789                 }
2790
2791                 [Test]
2792                 public void ListenNotBound ()
2793                 {
2794                         Socket sock = new Socket (AddressFamily.InterNetwork,
2795                                                   SocketType.Stream,
2796                                                   ProtocolType.Tcp);
2797                         
2798                         try {
2799                                 sock.Listen (1);
2800                                 Assert.Fail ("ListenNotBound #1");
2801                         } catch (SocketException ex) {
2802                                 Assert.AreEqual (10022, ex.ErrorCode, "ListenNotBound #2");
2803                         } finally {
2804                                 sock.Close ();
2805                         }
2806                 }
2807
2808                 static Socket CWRSocket;
2809                 static bool CWRReceiving = true;
2810                 static ManualResetEvent CWRReady = new ManualResetEvent (false);
2811                 
2812                 private static void CWRReceiveThread ()
2813                 {
2814                         byte[] buf = new byte[256];
2815                         
2816                         try {
2817                                 CWRSocket.Receive (buf);
2818                         } catch (SocketException) {
2819                                 CWRReceiving = false;
2820                         }
2821
2822                         CWRReady.Set ();
2823                 }
2824                 
2825                 [Test]
2826 #if FEATURE_NO_BSD_SOCKETS
2827                 [ExpectedException (typeof (PlatformNotSupportedException))]
2828 #endif
2829                 public void CloseWhileReceiving ()
2830                 {
2831                         CWRSocket = new Socket (AddressFamily.InterNetwork,
2832                                                 SocketType.Dgram,
2833                                                 ProtocolType.Udp);
2834                         CWRSocket.Bind (new IPEndPoint (IPAddress.Loopback,
2835                                                         NetworkHelpers.FindFreePort ()));
2836                         
2837                         Thread recv_thread = new Thread (new ThreadStart (CWRReceiveThread));
2838                         CWRReady.Reset ();
2839                         recv_thread.Start ();
2840                         Thread.Sleep (250);     /* Wait for the thread to be already receiving */
2841
2842                         CWRSocket.Close ();
2843                         if (CWRReady.WaitOne (1000, false) == false) {
2844                                 Assert.Fail ("CloseWhileReceiving wait timed out");
2845                         }
2846                         
2847                         Assert.IsFalse (CWRReceiving);
2848                 }
2849
2850                 static bool RRCLastRead = false;
2851                 static ManualResetEvent RRCReady = new ManualResetEvent (false);
2852                 
2853                 private static void RRCClientThread (int port)
2854                 {
2855                         byte[] bytes = new byte[8];
2856                         int readbyte;
2857                         
2858                         Socket sock = new Socket (AddressFamily.InterNetwork,
2859                                                   SocketType.Stream,
2860                                                   ProtocolType.Tcp);
2861                         sock.Connect (new IPEndPoint (IPAddress.Loopback,
2862                                                       port));
2863                         
2864                         NetworkStream stream = new NetworkStream (sock);
2865
2866                         readbyte = stream.ReadByte ();
2867                         Assert.AreEqual (0, readbyte, "ReceiveRemoteClosed #1");
2868                         
2869                         stream.Read (bytes, 0, 0);
2870
2871                         readbyte = stream.ReadByte ();
2872                         Assert.AreEqual (0, readbyte, "ReceiveRemoteClosed #2");
2873                         
2874                         stream.Read (bytes, 0, 0);
2875
2876                         readbyte = stream.ReadByte ();
2877                         Assert.AreEqual (-1, readbyte, "ReceiveRemoteClosed #3");
2878
2879                         sock.Close ();
2880
2881                         RRCLastRead = true;
2882                         RRCReady.Set ();
2883                 }
2884
2885                 [Test] // Receive (Byte [])
2886                 public void Receive1_Buffer_Null ()
2887                 {
2888                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2889                                 ProtocolType.Tcp);
2890
2891                         try {
2892                                 s.Receive ((byte []) null);
2893                                 Assert.Fail ("#1");
2894                         } catch (ArgumentNullException ex) {
2895                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2896                                 Assert.IsNull (ex.InnerException, "#3");
2897                                 Assert.IsNotNull (ex.Message, "#4");
2898                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
2899                         } finally {
2900                                 s.Close ();
2901                         }
2902                 }
2903
2904                 [Test] // Receive (Byte [])
2905                 public void Receive1_Socket_Closed ()
2906                 {
2907                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2908                                 ProtocolType.Tcp);
2909                         s.Close ();
2910
2911                         try {
2912                                 s.Receive ((byte []) null);
2913                                 Assert.Fail ("#1");
2914                         } catch (ObjectDisposedException ex) {
2915                                 // Cannot access a disposed object
2916                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
2917                                 Assert.IsNull (ex.InnerException, "#3");
2918                                 Assert.IsNotNull (ex.Message, "#4");
2919                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
2920                         }
2921                 }
2922
2923                 [Test] // Receive (Byte [], SocketFlags)
2924                 public void Receive2_Buffer_Null ()
2925                 {
2926                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2927                                 ProtocolType.Tcp);
2928
2929                         try {
2930                                 s.Receive ((byte []) null, (SocketFlags) 666);
2931                                 Assert.Fail ("#1");
2932                         } catch (ArgumentNullException ex) {
2933                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2934                                 Assert.IsNull (ex.InnerException, "#3");
2935                                 Assert.IsNotNull (ex.Message, "#4");
2936                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
2937                         } finally {
2938                                 s.Close ();
2939                         }
2940                 }
2941
2942                 [Test] // Receive (Byte [], SocketFlags)
2943                 public void Receive2_Socket_Closed ()
2944                 {
2945                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2946                                 ProtocolType.Tcp);
2947                         s.Close ();
2948
2949                         try {
2950                                 s.Receive ((byte []) null, (SocketFlags) 666);
2951                                 Assert.Fail ("#1");
2952                         } catch (ObjectDisposedException ex) {
2953                                 // Cannot access a disposed object
2954                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
2955                                 Assert.IsNull (ex.InnerException, "#3");
2956                                 Assert.IsNotNull (ex.Message, "#4");
2957                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
2958                         }
2959                 }
2960
2961                 [Test] // Receive (Byte [], Int32, SocketFlags)
2962                 public void Receive3_Buffer_Null ()
2963                 {
2964                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2965                                 ProtocolType.Tcp);
2966
2967                         try {
2968                                 s.Receive ((byte []) null, 0, (SocketFlags) 666);
2969                                 Assert.Fail ("#1");
2970                         } catch (ArgumentNullException ex) {
2971                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
2972                                 Assert.IsNull (ex.InnerException, "#3");
2973                                 Assert.IsNotNull (ex.Message, "#4");
2974                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
2975                         } finally {
2976                                 s.Close ();
2977                         }
2978                 }
2979
2980                 [Test] // Receive (Byte [], Int32, SocketFlags)
2981                 public void Receive3_Socket_Closed ()
2982                 {
2983                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
2984                                 ProtocolType.Tcp);
2985                         s.Close ();
2986
2987                         try {
2988                                 s.Receive ((byte []) null, 0, (SocketFlags) 666);
2989                                 Assert.Fail ("#1");
2990                         } catch (ObjectDisposedException ex) {
2991                                 // Cannot access a disposed object
2992                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
2993                                 Assert.IsNull (ex.InnerException, "#3");
2994                                 Assert.IsNotNull (ex.Message, "#4");
2995                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
2996                         }
2997                 }
2998
2999                 [Test] // Receive (Byte [], Int32, Int32, SocketFlags)
3000                 public void Receive4_Buffer_Null ()
3001                 {
3002                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3003                                 ProtocolType.Tcp);
3004
3005                         try {
3006                                 s.Receive ((byte []) null, 0, 0, (SocketFlags) 666);
3007                                 Assert.Fail ("#1");
3008                         } catch (ArgumentNullException ex) {
3009                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3010                                 Assert.IsNull (ex.InnerException, "#3");
3011                                 Assert.IsNotNull (ex.Message, "#4");
3012                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3013                         } finally {
3014                                 s.Close ();
3015                         }
3016                 }
3017
3018                 [Test] // Receive (Byte [], Int32, Int32, SocketFlags)
3019                 public void Receive4_Socket_Closed ()
3020                 {
3021                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3022                                 ProtocolType.Tcp);
3023                         s.Close ();
3024
3025                         try {
3026                                 s.Receive ((byte []) null, 0, 0, (SocketFlags) 666);
3027                                 Assert.Fail ("#1");
3028                         } catch (ObjectDisposedException ex) {
3029                                 // Cannot access a disposed object
3030                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3031                                 Assert.IsNull (ex.InnerException, "#3");
3032                                 Assert.IsNotNull (ex.Message, "#4");
3033                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3034                         }
3035                 }
3036
3037                 [Test] // Receive (Byte [], Int32, Int32, SocketFlags, out SocketError)
3038                 public void Receive5_Buffer_Null ()
3039                 {
3040                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3041                                 ProtocolType.Tcp);
3042
3043                         SocketError error;
3044                         try {
3045                                 s.Receive ((byte []) null, 0, 0, SocketFlags.None, out error);
3046                                 Assert.Fail ("#1");
3047                         } catch (ArgumentNullException ex) {
3048                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3049                                 Assert.IsNull (ex.InnerException, "#3");
3050                                 Assert.IsNotNull (ex.Message, "#4");
3051                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3052                         } finally {
3053                                 s.Close ();
3054                         }
3055                 }
3056
3057                 [Test] // Receive (Byte [], Int32, Int32, SocketFlags, out SocketError)
3058                 public void Receive5_Socket_Closed ()
3059                 {
3060                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3061                                 ProtocolType.Tcp);
3062                         s.Close ();
3063
3064                         SocketError error;
3065                         try {
3066                                 s.Receive ((byte []) null, 0, 0, SocketFlags.None, out error);
3067                                 Assert.Fail ("#1");
3068                         } catch (ObjectDisposedException ex) {
3069                                 // Cannot access a disposed object
3070                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3071                                 Assert.IsNull (ex.InnerException, "#3");
3072                                 Assert.IsNotNull (ex.Message, "#4");
3073                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3074                         }
3075                 }
3076
3077                 [Test] // Receive (IList<ArraySegment<Byte>>)
3078                 public void Receive6_Buffers_Null ()
3079                 {
3080                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3081                                 ProtocolType.Tcp);
3082
3083                         try {
3084                                 s.Receive ((IList<ArraySegment<byte>>) null);
3085                                 Assert.Fail ("#1");
3086                         } catch (ArgumentNullException ex) {
3087                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3088                                 Assert.IsNull (ex.InnerException, "#3");
3089                                 Assert.IsNotNull (ex.Message, "#4");
3090                                 Assert.AreEqual ("buffers", ex.ParamName, "#5");
3091                         } finally {
3092                                 s.Close ();
3093                         }
3094                 }
3095
3096                 [Test] // Receive (IList<ArraySegment<Byte>>)
3097                 public void Receive6_Socket_Closed ()
3098                 {
3099                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3100                                 ProtocolType.Tcp);
3101                         s.Close ();
3102
3103                         try {
3104                                 s.Receive ((IList<ArraySegment<byte>>) null);
3105                                 Assert.Fail ("#1");
3106                         } catch (ObjectDisposedException ex) {
3107                                 // Cannot access a disposed object
3108                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3109                                 Assert.IsNull (ex.InnerException, "#3");
3110                                 Assert.IsNotNull (ex.Message, "#4");
3111                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3112                         }
3113                 }
3114
3115                 [Test] // Receive (IList<ArraySegment<Byte>>, SocketFlags)
3116                 public void Receive7_Buffers_Null ()
3117                 {
3118                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3119                                 ProtocolType.Tcp);
3120
3121                         try {
3122                                 s.Receive ((IList<ArraySegment<byte>>) null, (SocketFlags) 666);
3123                                 Assert.Fail ("#1");
3124                         } catch (ArgumentNullException ex) {
3125                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3126                                 Assert.IsNull (ex.InnerException, "#3");
3127                                 Assert.IsNotNull (ex.Message, "#4");
3128                                 Assert.AreEqual ("buffers", ex.ParamName, "#5");
3129                         } finally {
3130                                 s.Close ();
3131                         }
3132                 }
3133
3134                 [Test] // Receive (IList<ArraySegment<Byte>>, SocketFlags)
3135                 public void Receive7_Socket_Closed ()
3136                 {
3137                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3138                                 ProtocolType.Tcp);
3139                         s.Close ();
3140
3141                         try {
3142                                 s.Receive ((IList<ArraySegment<byte>>) null, (SocketFlags) 666);
3143                                 Assert.Fail ("#1");
3144                         } catch (ObjectDisposedException ex) {
3145                                 // Cannot access a disposed object
3146                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3147                                 Assert.IsNull (ex.InnerException, "#3");
3148                                 Assert.IsNotNull (ex.Message, "#4");
3149                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3150                         }
3151                 }
3152
3153                 [Test] // Receive (IList<ArraySegment<Byte>>, SocketFlags, out SocketError)
3154                 public void Receive8_Buffers_Null ()
3155                 {
3156                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3157                                 ProtocolType.Tcp);
3158
3159                         SocketError error;
3160                         try {
3161                                 s.Receive ((IList<ArraySegment<byte>>) null, (SocketFlags) 666,
3162                                         out error);
3163                                 Assert.Fail ("#1");
3164                         } catch (ArgumentNullException ex) {
3165                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3166                                 Assert.IsNull (ex.InnerException, "#3");
3167                                 Assert.IsNotNull (ex.Message, "#4");
3168                                 Assert.AreEqual ("buffers", ex.ParamName, "#5");
3169                         } finally {
3170                                 s.Close ();
3171                         }
3172                 }
3173
3174                 [Test] // Receive (IList<ArraySegment<Byte>>, SocketFlags, out SocketError)
3175                 public void Receive8_Socket_Closed ()
3176                 {
3177                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3178                                 ProtocolType.Tcp);
3179                         s.Close ();
3180
3181                         SocketError error;
3182                         try {
3183                                 s.Receive ((IList<ArraySegment<byte>>) null, (SocketFlags) 666,
3184                                         out error);
3185                                 Assert.Fail ("#1");
3186                         } catch (ObjectDisposedException ex) {
3187                                 // Cannot access a disposed object
3188                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3189                                 Assert.IsNull (ex.InnerException, "#3");
3190                                 Assert.IsNotNull (ex.Message, "#4");
3191                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3192                         } finally {
3193                                 s.Close ();
3194                         }
3195                 }
3196
3197                 [Test] // ReceiveFrom (Byte [], ref EndPoint)
3198 #if FEATURE_NO_BSD_SOCKETS
3199                 [ExpectedException (typeof (PlatformNotSupportedException))]
3200 #endif
3201                 public void ReceiveFrom1_Buffer_Null ()
3202                 {
3203                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3204                                 ProtocolType.Tcp);
3205
3206                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3207                         try {
3208                                 s.ReceiveFrom ((Byte []) null, ref remoteEP);
3209                                 Assert.Fail ("#1");
3210                         } catch (ArgumentNullException ex) {
3211                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3212                                 Assert.IsNull (ex.InnerException, "#3");
3213                                 Assert.IsNotNull (ex.Message, "#4");
3214                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3215                         } finally {
3216                                 s.Close ();
3217                         }
3218                 }
3219
3220                 [Test] // ReceiveFrom (Byte [], ref EndPoint)
3221                 public void ReceiveFrom1_RemoteEP_Null ()
3222                 {
3223                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3224                                 ProtocolType.Tcp);
3225
3226                         byte [] buffer = new byte [0];
3227                         EndPoint remoteEP = null;
3228                         try {
3229                                 s.ReceiveFrom (buffer, ref remoteEP);
3230                                 Assert.Fail ("#1");
3231                         } catch (ArgumentNullException ex) {
3232                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3233                                 Assert.IsNull (ex.InnerException, "#3");
3234                                 Assert.IsNotNull (ex.Message, "#4");
3235                                 Assert.AreEqual ("remoteEP", ex.ParamName, "#5");
3236                         } finally {
3237                                 s.Close ();
3238                         }
3239                 }
3240
3241                 [Test] // ReceiveFrom (Byte [], ref EndPoint)
3242 #if FEATURE_NO_BSD_SOCKETS
3243                 [ExpectedException (typeof (PlatformNotSupportedException))]
3244 #endif
3245                 public void ReceiveFrom1_Socket_Closed ()
3246                 {
3247                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3248                                 ProtocolType.Tcp);
3249                         s.Close ();
3250
3251                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3252                         try {
3253                                 s.ReceiveFrom ((Byte []) null, ref remoteEP);
3254                                 Assert.Fail ("#1");
3255                         } catch (ObjectDisposedException ex) {
3256                                 // Cannot access a disposed object
3257                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3258                                 Assert.IsNull (ex.InnerException, "#3");
3259                                 Assert.IsNotNull (ex.Message, "#4");
3260                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3261                         }
3262                 }
3263
3264                 [Test] // ReceiveFrom (Byte [], SocketFlags, ref EndPoint)
3265 #if FEATURE_NO_BSD_SOCKETS
3266                 [ExpectedException (typeof (PlatformNotSupportedException))]
3267 #endif
3268                 public void ReceiveFrom2_Buffer_Null ()
3269                 {
3270                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3271                                 ProtocolType.Tcp);
3272
3273                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3274                         try {
3275                                 s.ReceiveFrom ((Byte []) null, (SocketFlags) 666, ref remoteEP);
3276                                 Assert.Fail ("#1");
3277                         } catch (ArgumentNullException ex) {
3278                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3279                                 Assert.IsNull (ex.InnerException, "#3");
3280                                 Assert.IsNotNull (ex.Message, "#4");
3281                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3282                         } finally {
3283                                 s.Close ();
3284                         }
3285                 }
3286
3287                 [Test] // ReceiveFrom (Byte [], SocketFlags, ref EndPoint)
3288                 public void ReceiveFrom2_RemoteEP_Null ()
3289                 {
3290                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3291                                 ProtocolType.Tcp);
3292
3293                         byte [] buffer = new byte [5];
3294                         EndPoint remoteEP = null;
3295                         try {
3296                                 s.ReceiveFrom (buffer, (SocketFlags) 666, ref remoteEP);
3297                                 Assert.Fail ("#1");
3298                         } catch (ArgumentNullException ex) {
3299                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3300                                 Assert.IsNull (ex.InnerException, "#3");
3301                                 Assert.IsNotNull (ex.Message, "#4");
3302                                 Assert.AreEqual ("remoteEP", ex.ParamName, "#5");
3303                         } finally {
3304                                 s.Close ();
3305                         }
3306                 }
3307
3308                 [Test] // ReceiveFrom (Byte [], SocketFlags, ref EndPoint)
3309 #if FEATURE_NO_BSD_SOCKETS
3310                 [ExpectedException (typeof (PlatformNotSupportedException))]
3311 #endif
3312                 public void ReceiveFrom2_Socket_Closed ()
3313                 {
3314                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3315                                 ProtocolType.Tcp);
3316                         s.Close ();
3317
3318                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3319                         try {
3320                                 s.ReceiveFrom ((Byte []) null, (SocketFlags) 666, ref remoteEP);
3321                                 Assert.Fail ("#1");
3322                         } catch (ObjectDisposedException ex) {
3323                                 // Cannot access a disposed object
3324                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3325                                 Assert.IsNull (ex.InnerException, "#3");
3326                                 Assert.IsNotNull (ex.Message, "#4");
3327                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3328                         }
3329                 }
3330
3331                 [Test] // ReceiveFrom (Byte [], Int32, SocketFlags, ref EndPoint)
3332 #if FEATURE_NO_BSD_SOCKETS
3333                 [ExpectedException (typeof (PlatformNotSupportedException))]
3334 #endif
3335                 public void ReceiveFrom3_Buffer_Null ()
3336                 {
3337                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3338                                 ProtocolType.Tcp);
3339
3340                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3341                         try {
3342                                 s.ReceiveFrom ((Byte []) null, 0, (SocketFlags) 666,
3343                                         ref remoteEP);
3344                                 Assert.Fail ("#1");
3345                         } catch (ArgumentNullException ex) {
3346                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3347                                 Assert.IsNull (ex.InnerException, "#3");
3348                                 Assert.IsNotNull (ex.Message, "#4");
3349                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3350                         } finally {
3351                                 s.Close ();
3352                         }
3353                 }
3354
3355                 [Test] // ReceiveFrom (Byte [], Int32, SocketFlags, ref EndPoint)
3356                 public void ReceiveFrom3_RemoteEP_Null ()
3357                 {
3358                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3359                                 ProtocolType.Tcp);
3360
3361                         byte [] buffer = new byte [5];
3362                         EndPoint remoteEP = null;
3363                         try {
3364                                 s.ReceiveFrom (buffer, buffer.Length, (SocketFlags) 666, ref remoteEP);
3365                                 Assert.Fail ("#1");
3366                         } catch (ArgumentNullException ex) {
3367                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3368                                 Assert.IsNull (ex.InnerException, "#3");
3369                                 Assert.IsNotNull (ex.Message, "#4");
3370                                 Assert.AreEqual ("remoteEP", ex.ParamName, "#5");
3371                         } finally {
3372                                 s.Close ();
3373                         }
3374                 }
3375
3376                 [Test] // ReceiveFrom (Byte [], Int32, SocketFlags, ref EndPoint)
3377 #if FEATURE_NO_BSD_SOCKETS
3378                 [ExpectedException (typeof (PlatformNotSupportedException))]
3379 #endif
3380                 public void ReceiveFrom3_Size_OutOfRange ()
3381                 {
3382                         Socket s;
3383                         byte [] buffer = new byte [5];
3384                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3385
3386                         // size negative
3387                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3388                                                         ProtocolType.Tcp);
3389                         try {
3390                                 s.ReceiveFrom (buffer, -1, (SocketFlags) 666, ref remoteEP);
3391                                 Assert.Fail ("#A1");
3392                         } catch (ArgumentOutOfRangeException ex) {
3393                                 // Specified argument was out of the range of valid values
3394                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
3395                                 Assert.IsNull (ex.InnerException, "#A3");
3396                                 Assert.IsNotNull (ex.Message, "#A4");
3397                                 Assert.AreEqual ("size", ex.ParamName, "#A5");
3398                         } finally {
3399                                 s.Close ();
3400                         }
3401
3402                         // size > buffer length
3403                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3404                                                         ProtocolType.Tcp);
3405                         try {
3406                                 s.ReceiveFrom (buffer, (buffer.Length + 1), (SocketFlags) 666,
3407                                         ref remoteEP);
3408                                 Assert.Fail ("#B1");
3409                         } catch (ArgumentOutOfRangeException ex) {
3410                                 // Specified argument was out of the range of valid values
3411                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#B2");
3412                                 Assert.IsNull (ex.InnerException, "#B3");
3413                                 Assert.IsNotNull (ex.Message, "#B4");
3414                                 Assert.AreEqual ("size", ex.ParamName, "#B5");
3415                         } finally {
3416                                 s.Close ();
3417                         }
3418                 }
3419
3420                 [Test] // ReceiveFrom (Byte [], Int32, SocketFlags, ref EndPoint)
3421 #if FEATURE_NO_BSD_SOCKETS
3422                 [ExpectedException (typeof (PlatformNotSupportedException))]
3423 #endif
3424                 public void ReceiveFrom3_Socket_Closed ()
3425                 {
3426                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3427                                 ProtocolType.Tcp);
3428                         s.Close ();
3429
3430                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3431                         try {
3432                                 s.ReceiveFrom ((Byte []) null, -1, (SocketFlags) 666,
3433                                         ref remoteEP);
3434                                 Assert.Fail ("#1");
3435                         } catch (ObjectDisposedException ex) {
3436                                 // Cannot access a disposed object
3437                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3438                                 Assert.IsNull (ex.InnerException, "#3");
3439                                 Assert.IsNotNull (ex.Message, "#4");
3440                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3441                         }
3442                 }
3443
3444                 [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, EndPoint)
3445 #if FEATURE_NO_BSD_SOCKETS
3446                 [ExpectedException (typeof (PlatformNotSupportedException))]
3447 #endif
3448                 public void ReceiveFrom4_Buffer_Null ()
3449                 {
3450                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3451                                 ProtocolType.Tcp);
3452                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3453
3454                         try {
3455                                 s.ReceiveFrom ((Byte []) null, -1, -1, (SocketFlags) 666,
3456                                         ref remoteEP);
3457                                 Assert.Fail ("#1");
3458                         } catch (ArgumentNullException ex) {
3459                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3460                                 Assert.IsNull (ex.InnerException, "#3");
3461                                 Assert.IsNotNull (ex.Message, "#4");
3462                                 Assert.AreEqual ("buffer", ex.ParamName, "#5");
3463                         }
3464                 }
3465
3466                 [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, EndPoint)
3467 #if FEATURE_NO_BSD_SOCKETS
3468                 [ExpectedException (typeof (PlatformNotSupportedException))]
3469 #endif
3470                 public void ReceiveFrom4_Offset_OutOfRange ()
3471                 {
3472                         Socket s;
3473                         byte [] buffer = new byte [5];
3474                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3475
3476                         // offset negative
3477                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3478                                                         ProtocolType.Tcp);
3479                         try {
3480                                 s.ReceiveFrom (buffer, -1, 0, (SocketFlags) 666,
3481                                         ref remoteEP);
3482                                 Assert.Fail ("#A1");
3483                         } catch (ArgumentOutOfRangeException ex) {
3484                                 // Specified argument was out of the range of valid values
3485                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
3486                                 Assert.IsNull (ex.InnerException, "#A3");
3487                                 Assert.IsNotNull (ex.Message, "#A4");
3488                                 Assert.AreEqual ("offset", ex.ParamName, "#A5");
3489                         } finally {
3490                                 s.Close ();
3491                         }
3492
3493                         // offset > buffer length
3494                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3495                                                         ProtocolType.Tcp);
3496                         try {
3497                                 s.ReceiveFrom (buffer, (buffer.Length + 1), 0, (SocketFlags) 666,
3498                                         ref remoteEP);
3499                                 Assert.Fail ("#B1");
3500                         } catch (ArgumentOutOfRangeException ex) {
3501                                 // Specified argument was out of the range of valid values
3502                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#B2");
3503                                 Assert.IsNull (ex.InnerException, "#B3");
3504                                 Assert.IsNotNull (ex.Message, "#B4");
3505                                 Assert.AreEqual ("offset", ex.ParamName, "#B5");
3506                         } finally {
3507                                 s.Close ();
3508                         }
3509                 }
3510
3511                 [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, ref IPEndPoint)
3512                 public void ReceiveFrom4_RemoteEP_Null ()
3513                 {
3514                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3515                                 ProtocolType.Tcp);
3516                         byte [] buffer = new byte [5];
3517                         EndPoint remoteEP = null;
3518
3519                         try {
3520                                 s.ReceiveFrom (buffer, 0, buffer.Length, (SocketFlags) 666, ref remoteEP);
3521                                 Assert.Fail ("#1");
3522                         } catch (ArgumentNullException ex) {
3523                                 Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
3524                                 Assert.IsNull (ex.InnerException, "#3");
3525                                 Assert.IsNotNull (ex.Message, "#4");
3526                                 Assert.AreEqual ("remoteEP", ex.ParamName, "#5");
3527                         } finally {
3528                                 s.Close ();
3529                         }
3530                 }
3531
3532                 [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, EndPoint)
3533 #if FEATURE_NO_BSD_SOCKETS
3534                 [ExpectedException (typeof (PlatformNotSupportedException))]
3535 #endif
3536                 public void ReceiveFrom4_Size_OutOfRange ()
3537                 {
3538                         Socket s;
3539                         byte [] buffer = new byte [5];
3540                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3541
3542                         // size negative
3543                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3544                                                         ProtocolType.Tcp);
3545                         try {
3546                                 s.ReceiveFrom (buffer, 0, -1, (SocketFlags) 666,
3547                                         ref remoteEP);
3548                                 Assert.Fail ("#A1");
3549                         } catch (ArgumentOutOfRangeException ex) {
3550                                 // Specified argument was out of the range of valid values
3551                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#A2");
3552                                 Assert.IsNull (ex.InnerException, "#A3");
3553                                 Assert.IsNotNull (ex.Message, "#A4");
3554                                 Assert.AreEqual ("size", ex.ParamName, "#A5");
3555                         } finally {
3556                                 s.Close ();
3557                         }
3558
3559                         // size > buffer length
3560                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3561                                                         ProtocolType.Tcp);
3562                         try {
3563                                 s.ReceiveFrom (buffer, 0, (buffer.Length + 1), (SocketFlags) 666,
3564                                         ref remoteEP);
3565                                 Assert.Fail ("#B1");
3566                         } catch (ArgumentOutOfRangeException ex) {
3567                                 // Specified argument was out of the range of valid values
3568                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#B2");
3569                                 Assert.IsNull (ex.InnerException, "#B3");
3570                                 Assert.IsNotNull (ex.Message, "#B4");
3571                                 Assert.AreEqual ("size", ex.ParamName, "#B5");
3572                         } finally {
3573                                 s.Close ();
3574                         }
3575
3576                         // offset + size > buffer length
3577                         s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3578                                                         ProtocolType.Tcp);
3579                         try {
3580                                 s.ReceiveFrom (buffer, 2, 4, (SocketFlags) 666, ref remoteEP);
3581                                 Assert.Fail ("#C1");
3582                         } catch (ArgumentOutOfRangeException ex) {
3583                                 // Specified argument was out of the range of valid values
3584                                 Assert.AreEqual (typeof (ArgumentOutOfRangeException), ex.GetType (), "#C2");
3585                                 Assert.IsNull (ex.InnerException, "#C3");
3586                                 Assert.IsNotNull (ex.Message, "#C4");
3587                                 Assert.AreEqual ("size", ex.ParamName, "#C5");
3588                         } finally {
3589                                 s.Close ();
3590                         }
3591                 }
3592
3593                 [Test] // ReceiveFrom (Byte [], Int32, Int32, SocketFlags, ref EndPoint)
3594 #if FEATURE_NO_BSD_SOCKETS
3595                 [ExpectedException (typeof (PlatformNotSupportedException))]
3596 #endif
3597                 public void ReceiveFrom4_Socket_Closed ()
3598                 {
3599                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
3600                                 ProtocolType.Tcp);
3601                         s.Close ();
3602
3603                         byte [] buffer = new byte [5];
3604                         EndPoint remoteEP = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3605                         try {
3606                                 s.ReceiveFrom (buffer, -1, -1, (SocketFlags) 666,
3607                                         ref remoteEP);
3608                                 Assert.Fail ("#1");
3609                         } catch (ObjectDisposedException ex) {
3610                                 // Cannot access a disposed object
3611                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3612                                 Assert.IsNull (ex.InnerException, "#3");
3613                                 Assert.IsNotNull (ex.Message, "#4");
3614                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3615                         }
3616                 }
3617
3618                 [Test]
3619 #if FEATURE_NO_BSD_SOCKETS
3620                 [ExpectedException (typeof (PlatformNotSupportedException))]
3621 #endif
3622                 public void ReceiveRemoteClosed ()
3623                 {
3624                         var port = NetworkHelpers.FindFreePort ();
3625                         Socket sock = new Socket (AddressFamily.InterNetwork,
3626                                                   SocketType.Stream,
3627                                                   ProtocolType.Tcp);
3628                         sock.Bind (new IPEndPoint (IPAddress.Loopback, port));
3629                         sock.Listen (1);
3630                         
3631                         RRCReady.Reset ();
3632                         Thread client_thread = new Thread (() => RRCClientThread (port));
3633                         client_thread.Start ();
3634                         
3635                         Socket client = sock.Accept ();
3636                         NetworkStream stream = new NetworkStream (client);
3637                         stream.WriteByte (0x00);
3638                         stream.WriteByte (0x00);
3639                         client.Close ();
3640                         sock.Close ();
3641
3642                         RRCReady.WaitOne (1000, false);
3643                         Assert.IsTrue (RRCLastRead);
3644                 }
3645
3646                 //
3647                 // Test case for bug #471580
3648                 [Test]
3649 #if FEATURE_NO_BSD_SOCKETS
3650                 [ExpectedException (typeof (PlatformNotSupportedException))]
3651 #endif
3652                 public void UdpDoubleBind ()
3653                 {
3654                         using (Socket s = new Socket (AddressFamily.InterNetwork,
3655                                                 SocketType.Dgram, ProtocolType.Udp))
3656                         using (Socket ss = new Socket (AddressFamily.InterNetwork,
3657                                                 SocketType.Dgram, ProtocolType.Udp)) {
3658                                 var supportsReuseAddress = true;
3659                                 try {
3660                                         s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
3661                                 } catch (SocketException e) {
3662                                         // Exception is thrown when ReuseAddress is not supported
3663                                         Assert.AreEqual ((int) SocketError.OperationNotSupported, e.NativeErrorCode,
3664                                                         "Expected SocketError.OperationNotSupported");
3665                                         supportsReuseAddress = false;
3666                                 }
3667
3668                                 var ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
3669                                 s.Bind (ep);
3670
3671                                 if (supportsReuseAddress)
3672                                         ss.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
3673
3674                                 try {
3675                                         ss.Bind (new IPEndPoint (IPAddress.Any, ep.Port));
3676                                         if (!supportsReuseAddress)
3677                                                 Assert.Fail ("Reusing address is not supported, exception was expected on second bind.");
3678                                 } catch (SocketException e) {
3679                                 }
3680                         }
3681                 }
3682
3683                 // Test case for bug #31557
3684                 [Test]
3685 #if FEATURE_NO_BSD_SOCKETS
3686                 [ExpectedException (typeof (PlatformNotSupportedException))]
3687 #endif
3688                 public void TcpDoubleBind ()
3689                 {
3690                         using (Socket s = new Socket (AddressFamily.InterNetwork,
3691                                                 SocketType.Stream, ProtocolType.Tcp))
3692                         using (Socket ss = new Socket (AddressFamily.InterNetwork,
3693                                                 SocketType.Stream, ProtocolType.Tcp)) {
3694                                 var supportsReuseAddress = true;
3695                                 try {
3696                                         s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
3697                                 } catch (SocketException e) {
3698                                         // Exception is thrown when ReuseAddress is not supported
3699                                         Assert.AreEqual ((int) SocketError.OperationNotSupported, e.NativeErrorCode,
3700                                                         "Expected SocketError.OperationNotSupported");
3701                                         supportsReuseAddress = false;
3702                                 }
3703
3704                                 var ep = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
3705                                 s.Bind (ep);
3706                                 s.Listen(1);
3707
3708                                 if (supportsReuseAddress)
3709                                         ss.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
3710
3711                                 try {
3712                                         ss.Bind (new IPEndPoint (IPAddress.Any, ep.Port));
3713                                         ss.Listen(1);
3714                                         if (!supportsReuseAddress)
3715                                                 Assert.Fail ("Reusing address is not supported, exception was expected on second bind.");
3716                                 } catch (SocketException e) {
3717                                 }
3718                         }
3719                 }
3720
3721                 [Test]
3722                 [Category ("NotOnMac")]
3723 #if FULL_AOT_DESKTOP
3724                 [Ignore ("https://bugzilla.xamarin.com/show_bug.cgi?id=52157")]
3725 #endif
3726                 public void ConnectedProperty ()
3727                 {
3728                         TcpListener listener = new TcpListener (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
3729                         listener.Start();
3730
3731                         Socket client = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3732                         client.Connect (IPAddress.Loopback, ((IPEndPoint)listener.LocalEndpoint).Port);
3733                         Socket server = listener.AcceptSocket ();
3734
3735                         try {
3736                                 server.EndSend(server.BeginSend (new byte[10], 0, 10, SocketFlags.None, null, null));
3737                                 client.Close ();
3738                                 try {
3739                                         server.EndReceive (server.BeginReceive (new byte[10], 0, 10, SocketFlags.None, null, null));
3740                                 } catch {
3741                                 }
3742                                 Assert.IsTrue (!client.Connected);
3743                                 Assert.IsTrue (!server.Connected);
3744                         } finally {
3745                                 listener.Stop ();
3746                                 client.Close ();
3747                                 server.Close ();
3748                         }
3749                 }
3750
3751                 [Test] // GetSocketOption (SocketOptionLevel, SocketOptionName)
3752                 public void GetSocketOption1_Socket_Closed ()
3753                 {
3754                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3755                         s.Close ();
3756                         try {
3757                                 s.GetSocketOption (0, 0);
3758                                 Assert.Fail ("#1");
3759                         } catch (ObjectDisposedException ex) {
3760                                 // Cannot access a disposed object
3761                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3762                                 Assert.IsNull (ex.InnerException, "#3");
3763                                 Assert.IsNotNull (ex.Message, "#4");
3764                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3765                         }
3766                 }
3767
3768                 [Test] // GetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3769                 public void GetSocketOption2_OptionValue_Null ()
3770                 {
3771                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3772                         try {
3773                                 s.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
3774                                         (byte []) null);
3775                                 Assert.Fail ("#1");
3776                                 } catch (SocketException ex) {
3777                                         // The system detected an invalid pointer address in attempting
3778                                         // to use a pointer argument in a call
3779                                         Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
3780                                         Assert.AreEqual (10014, ex.ErrorCode, "#3");
3781                                         Assert.IsNull (ex.InnerException, "#4");
3782                                         Assert.IsNotNull (ex.Message, "#5");
3783                                         Assert.AreEqual (10014, ex.NativeErrorCode, "#6");
3784                                         Assert.AreEqual (SocketError.Fault, ex.SocketErrorCode, "#7");
3785                                 }
3786                 }
3787
3788                 [Test] // GetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3789                 public void GetSocketOption2_Socket_Closed ()
3790                 {
3791                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3792                         s.Close ();
3793                         try {
3794                                 s.GetSocketOption (0, 0, (byte []) null);
3795                                 Assert.Fail ("#1");
3796                         } catch (ObjectDisposedException ex) {
3797                                 // Cannot access a disposed object
3798                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3799                                 Assert.IsNull (ex.InnerException, "#3");
3800                                 Assert.IsNotNull (ex.Message, "#4");
3801                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3802                         }
3803                 }
3804
3805                 [Test] // GetSocketOption (SocketOptionLevel, SocketOptionName, Int32)
3806                 public void GetSocketOption3_Socket_Closed ()
3807                 {
3808                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3809                         s.Close ();
3810                         try {
3811                                 s.GetSocketOption (0, 0, 0);
3812                                 Assert.Fail ("#1");
3813                         } catch (ObjectDisposedException ex) {
3814                                 // Cannot access a disposed object
3815                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3816                                 Assert.IsNull (ex.InnerException, "#3");
3817                                 Assert.IsNotNull (ex.Message, "#4");
3818                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3819                         }
3820                 }
3821
3822                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3823                 public void SetSocketOption1_DontLinger ()
3824                 {
3825                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3826                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger,
3827                                         new byte [] { 0x00 });
3828                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger,
3829                                         new byte [] { 0x01 });
3830                         }
3831                 }
3832
3833                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3834                 public void SetSocketOption1_DontLinger_Null ()
3835                 {
3836                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3837                                 try {
3838                                         s.SetSocketOption (SocketOptionLevel.Socket,
3839                                                 SocketOptionName.DontLinger, (byte []) null);
3840                                         Assert.Fail ("#1");
3841                                 } catch (SocketException ex) {
3842                                         // The system detected an invalid pointer address in attempting
3843                                         // to use a pointer argument in a call
3844                                         Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
3845                                         Assert.AreEqual (10014, ex.ErrorCode, "#3");
3846                                         Assert.IsNull (ex.InnerException, "#4");
3847                                         Assert.IsNotNull (ex.Message, "#5");
3848                                         Assert.AreEqual (10014, ex.NativeErrorCode, "#6");
3849                                         Assert.AreEqual (SocketError.Fault, ex.SocketErrorCode, "#7");
3850                                 }
3851                         }
3852                 }
3853
3854                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3855                 public void SetSocketOption1_Linger_Null ()
3856                 {
3857                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3858                                 try {
3859                                         s.SetSocketOption (SocketOptionLevel.Socket,
3860                                                 SocketOptionName.DontLinger, (byte []) null);
3861                                         Assert.Fail ("#1");
3862                                 } catch (SocketException ex) {
3863                                         // The system detected an invalid pointer address in attempting
3864                                         // to use a pointer argument in a call
3865                                         Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
3866                                         Assert.AreEqual (10014, ex.ErrorCode, "#3");
3867                                         Assert.IsNull (ex.InnerException, "#4");
3868                                         Assert.IsNotNull (ex.Message, "#5");
3869                                         Assert.AreEqual (10014, ex.NativeErrorCode, "#6");
3870                                         Assert.AreEqual (SocketError.Fault, ex.SocketErrorCode, "#7");
3871                                 }
3872                         }
3873                 }
3874
3875                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Byte [])
3876                 public void SetSocketOption1_Socket_Close ()
3877                 {
3878                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3879                         s.Close ();
3880                         try {
3881                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger,
3882                                         new byte [] { 0x00 });
3883                                 Assert.Fail ("#1");
3884                         } catch (ObjectDisposedException ex) {
3885                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3886                                 Assert.IsNull (ex.InnerException, "#3");
3887                                 Assert.IsNotNull (ex.Message, "#4");
3888                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3889                         }
3890                 }
3891
3892                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Int32)
3893                 public void SetSocketOption2_DontLinger ()
3894                 {
3895                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3896                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger, 0);
3897                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger, 5);
3898                         }
3899                 }
3900
3901                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Int32)
3902                 [Category ("NotWorking")]
3903                 public void SetSocketOption2_Linger ()
3904                 {
3905                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
3906                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger, 0);
3907                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger, 5);
3908                         }
3909                 }
3910
3911                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Int32)
3912                 public void SetSocketOption2_Socket_Closed ()
3913                 {
3914                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
3915                         s.Close ();
3916                         try {
3917                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.DontLinger, 0);
3918                                 Assert.Fail ("#1");
3919                         } catch (ObjectDisposedException ex) {
3920                                 // Cannot access a disposed object
3921                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
3922                                 Assert.IsNull (ex.InnerException, "#3");
3923                                 Assert.IsNotNull (ex.Message, "#4");
3924                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
3925                         }
3926                 }
3927
3928                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3929 #if FEATURE_NO_BSD_SOCKETS
3930                 [ExpectedException (typeof (PlatformNotSupportedException))]
3931 #endif
3932                 public void SetSocketOption3_AddMembershipIPv4_IPv6MulticastOption ()
3933                 {
3934                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
3935
3936                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
3937                                 s.Bind (new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ()));
3938                                 try {
3939                                         s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
3940                                                 new IPv6MulticastOption (mcast_addr));
3941                                         Assert.Fail ("#1");
3942                                 } catch (ArgumentException ex) {
3943                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
3944                                         Assert.IsNull (ex.InnerException, "#3");
3945                                         Assert.IsNotNull (ex.Message, "#4");
3946                                         // The specified value is not a valid 'MulticastOption'
3947                                         Assert.IsTrue (ex.Message.IndexOf ("'MulticastOption'") != -1, "#5:" + ex.Message);
3948                                         Assert.AreEqual ("optionValue", ex.ParamName, "#6");
3949                                 }
3950                         }
3951                 }
3952
3953                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3954 #if FEATURE_NO_BSD_SOCKETS
3955                 [ExpectedException (typeof (PlatformNotSupportedException))]
3956 #endif
3957                 public void SetSocketOption3_AddMembershipIPv4_MulticastOption ()
3958                 {
3959                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
3960
3961                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
3962                                 s.Bind (new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ()));
3963                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
3964                                         new MulticastOption (mcast_addr));
3965                         }
3966                 }
3967
3968                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3969                 [Category ("NotWorking")]
3970                 public void SetSocketOption3_AddMembershipIPv4_Socket_NotBound ()
3971                 {
3972                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
3973
3974                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
3975                         try {
3976                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
3977                                         new MulticastOption (mcast_addr));
3978                                 Assert.Fail ("#1");
3979                         } catch (SocketException ex) {
3980                                 // An invalid argument was supplied
3981                                 Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
3982                                 Assert.AreEqual (10022, ex.ErrorCode, "#3");
3983                                 Assert.IsNull (ex.InnerException, "#4");
3984                                 Assert.IsNotNull (ex.Message, "#5");
3985                                 Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
3986                                 Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
3987                         } finally {
3988                                 s.Close ();
3989                         }
3990                 }
3991
3992                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
3993 #if FEATURE_NO_BSD_SOCKETS
3994                 [ExpectedException (typeof (PlatformNotSupportedException))]
3995 #endif
3996                 public void SetSocketOption3_AddMembershipIPv6_IPv6MulticastOption ()
3997                 {
3998                         if (!Socket.OSSupportsIPv6)
3999                                 Assert.Ignore ("IPv6 not enabled.");
4000
4001                         IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
4002
4003                         using (Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp)) {
4004                                 s.Bind (new IPEndPoint (IPAddress.IPv6Any, NetworkHelpers.FindFreePort ()));
4005                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
4006                                         new IPv6MulticastOption (mcast_addr));
4007                         }
4008                 }
4009
4010                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4011 #if FEATURE_NO_BSD_SOCKETS
4012                 [ExpectedException (typeof (PlatformNotSupportedException))]
4013 #endif
4014                 public void SetSocketOption3_AddMembershipIPv6_MulticastOption ()
4015                 {
4016                         if (!Socket.OSSupportsIPv6)
4017                                 Assert.Ignore ("IPv6 not enabled.");
4018
4019                         IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
4020
4021                         using (Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp)) {
4022                                 s.Bind (new IPEndPoint (IPAddress.IPv6Any, NetworkHelpers.FindFreePort ()));
4023                                 try {
4024                                         s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
4025                                                 new MulticastOption (mcast_addr));
4026                                         Assert.Fail ("#1");
4027                                 } catch (ArgumentException ex) {
4028                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
4029                                         Assert.IsNull (ex.InnerException, "#3");
4030                                         Assert.IsNotNull (ex.Message, "#4");
4031                                         // The specified value is not a valid 'IPv6MulticastOption'
4032                                         Assert.IsTrue (ex.Message.IndexOf ("'IPv6MulticastOption'") != -1, "#5:" + ex.Message);
4033                                         Assert.AreEqual ("optionValue", ex.ParamName, "#6");
4034                                 }
4035                         }
4036                 }
4037
4038                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4039                 [Category ("NotWorking")]
4040                 public void SetSocketOption3_AddMembershipIPv6_Socket_NotBound ()
4041                 {
4042                         IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
4043
4044                         Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
4045                         try {
4046                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
4047                                         new IPv6MulticastOption (mcast_addr));
4048                                 Assert.Fail ("#1");
4049                         } catch (SocketException ex) {
4050                                 // An invalid argument was supplied
4051                                 Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
4052                                 Assert.AreEqual (10022, ex.ErrorCode, "#3");
4053                                 Assert.IsNull (ex.InnerException, "#4");
4054                                 Assert.IsNotNull (ex.Message, "#5");
4055                                 Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
4056                                 Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
4057                         } finally {
4058                                 s.Close ();
4059                         }
4060                 }
4061
4062                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4063                 public void SetSocketOption3_DontLinger_Boolean ()
4064                 {
4065                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4066                                 try {
4067                                         s.SetSocketOption (SocketOptionLevel.Socket,
4068                                                 SocketOptionName.DontLinger, (object) false);
4069                                         Assert.Fail ("#1");
4070                                 } catch (ArgumentException ex) {
4071                                         // The specified value is not valid
4072                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
4073                                         Assert.IsNull (ex.InnerException, "#3");
4074                                         Assert.IsNotNull (ex.Message, "#4");
4075                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
4076                                 }
4077                         }
4078                 }
4079
4080                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4081                 public void SetSocketOption3_DontLinger_Int32 ()
4082                 {
4083                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4084                                 try {
4085                                         s.SetSocketOption (SocketOptionLevel.Socket,
4086                                                 SocketOptionName.DontLinger, (object) 0);
4087                                         Assert.Fail ("#1");
4088                                 } catch (ArgumentException ex) {
4089                                         // The specified value is not valid
4090                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
4091                                         Assert.IsNull (ex.InnerException, "#3");
4092                                         Assert.IsNotNull (ex.Message, "#4");
4093                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
4094                                 }
4095                         }
4096                 }
4097
4098                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4099                 public void SetSocketOption3_DontLinger_LingerOption ()
4100                 {
4101                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4102                                 try {
4103                                         s.SetSocketOption (SocketOptionLevel.Socket,
4104                                                 SocketOptionName.DontLinger, new LingerOption (true, 1000));
4105                                         Assert.Fail ("#1");
4106                                 } catch (ArgumentException ex) {
4107                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
4108                                         Assert.IsNull (ex.InnerException, "#3");
4109                                         // The specified value is not valid
4110                                         Assert.IsNotNull (ex.Message, "#4");
4111                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
4112                                 }
4113                         }
4114                 }
4115
4116                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4117                 public void SetSocketOption3_Linger_Boolean ()
4118                 {
4119                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4120                                 try {
4121                                         s.SetSocketOption (SocketOptionLevel.Socket,
4122                                                 SocketOptionName.Linger, (object) false);
4123                                         Assert.Fail ("#1");
4124                                 } catch (ArgumentException ex) {
4125                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
4126                                         Assert.IsNull (ex.InnerException, "#3");
4127                                         // The specified value is not valid
4128                                         Assert.IsNotNull (ex.Message, "#4");
4129                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
4130                                 }
4131                         }
4132                 }
4133
4134                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4135                 public void SetSocketOption3_Linger_Int32 ()
4136                 {
4137                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4138                                 try {
4139                                         s.SetSocketOption (SocketOptionLevel.Socket,
4140                                                 SocketOptionName.Linger, (object) 0);
4141                                         Assert.Fail ("#1");
4142                                 } catch (ArgumentException ex) {
4143                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
4144                                         Assert.IsNull (ex.InnerException, "#3");
4145                                         // The specified value is not valid
4146                                         Assert.IsNotNull (ex.Message, "#4");
4147                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
4148                                 }
4149                         }
4150                 }
4151
4152                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4153                 public void SetSocketOption3_Linger_LingerOption ()
4154                 {
4155                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4156                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
4157                                         new LingerOption (false, 0));
4158                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
4159                                         new LingerOption (true, 0));
4160                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
4161                                         new LingerOption (false, 1000));
4162                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
4163                                         new LingerOption (true, 1000));
4164                         }
4165                 }
4166
4167                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4168 #if FEATURE_NO_BSD_SOCKETS
4169                 [ExpectedException (typeof (PlatformNotSupportedException))]
4170 #endif
4171                 public void SetSocketOption3_DropMembershipIPv4_IPv6MulticastOption ()
4172                 {
4173                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
4174
4175                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
4176                                 s.Bind (new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ()));
4177                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
4178                                         new MulticastOption (mcast_addr));
4179                                 try {
4180                                         s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
4181                                                 new IPv6MulticastOption (mcast_addr));
4182                                         Assert.Fail ("#1");
4183                                 } catch (ArgumentException ex) {
4184                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
4185                                         Assert.IsNull (ex.InnerException, "#3");
4186                                         Assert.IsNotNull (ex.Message, "#4");
4187                                         // The specified value is not a valid 'MulticastOption'
4188                                         Assert.IsTrue (ex.Message.IndexOf ("'MulticastOption'") != -1, "#5:" + ex.Message);
4189                                         Assert.AreEqual ("optionValue", ex.ParamName, "#6");
4190                                 }
4191                         }
4192                 }
4193
4194                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4195 #if FEATURE_NO_BSD_SOCKETS
4196                 [ExpectedException (typeof (PlatformNotSupportedException))]
4197 #endif
4198                 public void SetSocketOption3_DropMembershipIPv4_MulticastOption ()
4199                 {
4200                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
4201
4202                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
4203                                 MulticastOption option = new MulticastOption (mcast_addr);
4204
4205                                 s.Bind (new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ()));
4206                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
4207                                         option);
4208                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
4209                                         option);
4210                         }
4211                 }
4212
4213                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4214                 [Category ("NotWorking")]
4215                 public void SetSocketOption3_DropMembershipIPv4_Socket_NotBound ()
4216                 {
4217                         IPAddress mcast_addr = IPAddress.Parse ("239.255.255.250");
4218
4219                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
4220                         try {
4221                                 s.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
4222                                         new MulticastOption (mcast_addr));
4223                                 Assert.Fail ("#1");
4224                         } catch (SocketException ex) {
4225                                 // An invalid argument was supplied
4226                                 Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
4227                                 Assert.AreEqual (10022, ex.ErrorCode, "#3");
4228                                 Assert.IsNull (ex.InnerException, "#4");
4229                                 Assert.IsNotNull (ex.Message, "#5");
4230                                 Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
4231                                 Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
4232                         } finally {
4233                                 s.Close ();
4234                         }
4235                 }
4236
4237                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4238 #if FEATURE_NO_BSD_SOCKETS
4239                 [ExpectedException (typeof (PlatformNotSupportedException))]
4240 #endif
4241                 public void SetSocketOption3_DropMembershipIPv6_IPv6MulticastOption ()
4242                 {
4243                         if (!Socket.OSSupportsIPv6)
4244                                 Assert.Ignore ("IPv6 not enabled.");
4245
4246                         using (Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp)) {
4247                                 IPv6MulticastOption option = new IPv6MulticastOption (
4248                                         IPAddress.Parse ("ff02::1"));
4249
4250                                 s.Bind (new IPEndPoint (IPAddress.IPv6Any, 1902));
4251                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
4252                                         option);
4253                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
4254                                         option);
4255                         }
4256                 }
4257
4258                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4259 #if FEATURE_NO_BSD_SOCKETS
4260                 [ExpectedException (typeof (PlatformNotSupportedException))]
4261 #endif
4262                 public void SetSocketOption3_DropMembershipIPv6_MulticastOption ()
4263                 {
4264                         if (!Socket.OSSupportsIPv6)
4265                                 Assert.Ignore ("IPv6 not enabled.");
4266
4267                         IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
4268
4269                         using (Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp)) {
4270                                 s.Bind (new IPEndPoint (IPAddress.IPv6Any, NetworkHelpers.FindFreePort ()));
4271                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
4272                                         new IPv6MulticastOption (mcast_addr));
4273                                 try {
4274                                         s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
4275                                                 new MulticastOption (mcast_addr));
4276                                         Assert.Fail ("#1");
4277                                 } catch (ArgumentException ex) {
4278                                         Assert.AreEqual (typeof (ArgumentException), ex.GetType (), "#2");
4279                                         Assert.IsNull (ex.InnerException, "#3");
4280                                         Assert.IsNotNull (ex.Message, "#4");
4281                                         // The specified value is not a valid 'IPv6MulticastOption'
4282                                         Assert.IsTrue (ex.Message.IndexOf ("'IPv6MulticastOption'") != -1, "#5:" + ex.Message);
4283                                         Assert.AreEqual ("optionValue", ex.ParamName, "#6");
4284                                 }
4285                         }
4286                 }
4287
4288                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4289                 [Category ("NotWorking")]
4290                 public void SetSocketOption3_DropMembershipIPv6_Socket_NotBound ()
4291                 {
4292                         IPAddress mcast_addr = IPAddress.Parse ("ff02::1");
4293
4294                         Socket s = new Socket (AddressFamily.InterNetworkV6, SocketType.Dgram, ProtocolType.Udp);
4295                         try {
4296                                 s.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
4297                                         new IPv6MulticastOption (mcast_addr));
4298                                 Assert.Fail ("#1");
4299                         } catch (SocketException ex) {
4300                                 // An invalid argument was supplied
4301                                 Assert.AreEqual (typeof (SocketException), ex.GetType (), "#2");
4302                                 Assert.AreEqual (10022, ex.ErrorCode, "#3");
4303                                 Assert.IsNull (ex.InnerException, "#4");
4304                                 Assert.IsNotNull (ex.Message, "#5");
4305                                 Assert.AreEqual (10022, ex.NativeErrorCode, "#6");
4306                                 Assert.AreEqual (SocketError.InvalidArgument, ex.SocketErrorCode, "#7");
4307                         } finally {
4308                                 s.Close ();
4309                         }
4310                 }
4311
4312                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4313                 public void SetSocketOption3_OptionValue_Null ()
4314                 {
4315                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4316                                 try {
4317                                         s.SetSocketOption (SocketOptionLevel.Socket,
4318                                                 SocketOptionName.Linger, (object) null);
4319                                         Assert.Fail ("#1");
4320                                 } catch (ArgumentNullException ex) {
4321                                         Assert.AreEqual (typeof (ArgumentNullException), ex.GetType (), "#2");
4322                                         Assert.IsNull (ex.InnerException, "#3");
4323                                         Assert.IsNotNull (ex.Message, "#4");
4324                                         Assert.AreEqual ("optionValue", ex.ParamName, "#5");
4325                                 }
4326                         }
4327                 }
4328
4329                 [Test] // SetSocketOption (SocketOptionLevel, SocketOptionName, Object)
4330                 public void SetSocketOption3_Socket_Closed ()
4331                 {
4332                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4333                         s.Close ();
4334                         try {
4335                                 s.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger,
4336                                         new LingerOption (false, 0));
4337                                 Assert.Fail ("#1");
4338                         } catch (ObjectDisposedException ex) {
4339                                 // Cannot access a disposed object
4340                                 Assert.AreEqual (typeof (ObjectDisposedException), ex.GetType (), "#2");
4341                                 Assert.IsNull (ex.InnerException, "#3");
4342                                 Assert.IsNotNull (ex.Message, "#4");
4343                                 Assert.AreEqual (typeof (Socket).FullName, ex.ObjectName, "#5");
4344                         }
4345                 }
4346
4347                 [Test]
4348                 [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.
4349                 public void SetSocketOption_MulticastInterfaceIndex_Any ()
4350                 {
4351                         IPAddress ip = IPAddress.Parse ("239.255.255.250");
4352                         int index = 0;
4353                         using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
4354                         {
4355                                 s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(index));
4356                                 s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, index));
4357                         }
4358                 }
4359
4360                 [Test]
4361                 [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.
4362                 public void SetSocketOption_MulticastInterfaceIndex_Loopback ()
4363                 {
4364                         IPAddress ip = IPAddress.Parse ("239.255.255.250");
4365                         int index = 1;
4366                         using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
4367                         {
4368                                 s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(index));
4369                                 s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, index));
4370                         }
4371                 }
4372
4373                 [Test]
4374                 public void SetSocketOption_MulticastInterfaceIndex_Invalid ()
4375                 {
4376                         IPAddress ip = IPAddress.Parse ("239.255.255.250");
4377                         int index = 31415;
4378                         using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
4379                         {
4380                                 try
4381                                 {
4382                                         s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastInterface, IPAddress.HostToNetworkOrder(index));
4383                                         Assert.Fail ("#1");
4384                                 }
4385                                 catch
4386                                 {}
4387                                 try
4388                                 {
4389                                         s.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(ip, index));
4390                                         Assert.Fail ("#2");
4391                                 }
4392                                 catch
4393                                 {}
4394                         }
4395                 }
4396
4397                 [Test]
4398 #if FEATURE_NO_BSD_SOCKETS
4399                 [ExpectedException (typeof (PlatformNotSupportedException))]
4400 #endif
4401                 public void Shutdown_NoConnect ()
4402                 {
4403                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4404                         s.Bind (new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ()));
4405                         s.Listen (1);
4406                         try {
4407                                 s.Shutdown (SocketShutdown.Both);
4408                                 Assert.Fail ("#1");
4409                         } catch (SocketException exc) {
4410                                 Assert.AreEqual (10057, exc.ErrorCode, "#2");
4411                         } finally {
4412                                 s.Close ();
4413                         }
4414                 }
4415
4416                 [Test]
4417                 [ExpectedException (typeof (NullReferenceException))]
4418                 public void ReceiveAsync_Null ()
4419                 {
4420                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4421                                 s.ReceiveAsync (null);
4422                         }
4423                 }
4424
4425                 [Test]
4426                 [ExpectedException (typeof (NullReferenceException))]
4427                 public void ReceiveAsync_Default ()
4428                 {
4429                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4430                                 SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
4431                                 s.ReceiveAsync (saea);
4432                         }
4433                 }
4434
4435
4436                 [Test]
4437                 [ExpectedException (typeof (NullReferenceException))]
4438                 public void ReceiveAsync_NullBuffer ()
4439                 {
4440                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4441                                 SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
4442                                 saea.SetBuffer (null, 0, 0);
4443                                 s.ReceiveAsync (null);
4444                         }
4445                 }
4446
4447                 [Test]
4448                 [ExpectedException (typeof (ObjectDisposedException))]
4449                 public void ReceiveAsync_ClosedSocket ()
4450                 {
4451                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4452                         s.Close ();
4453                         s.ReceiveAsync (null);
4454                 }
4455
4456                 [Test]
4457                 [ExpectedException (typeof (NullReferenceException))]
4458                 public void SendAsync_Null ()
4459                 {
4460                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4461                                 s.SendAsync (null);
4462                         }
4463                 }
4464
4465                 [Test]
4466                 [ExpectedException (typeof (NullReferenceException))]
4467                 public void SendAsync_Default ()
4468                 {
4469                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4470                                 SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
4471                                 s.SendAsync (saea);
4472                         }
4473                 }
4474
4475
4476                 [Test]
4477                 [ExpectedException (typeof (NullReferenceException))]
4478                 public void SendAsync_NullBuffer ()
4479                 {
4480                         using (Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) {
4481                                 SocketAsyncEventArgs saea = new SocketAsyncEventArgs ();
4482                                 saea.SetBuffer (null, 0, 0);
4483                                 s.SendAsync (null);
4484                         }
4485                 }
4486
4487                 [Test]
4488                 [ExpectedException (typeof (ObjectDisposedException))]
4489                 public void SendAsync_ClosedSocket ()
4490                 {
4491                         Socket s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4492                         s.Close ();
4493                         s.SendAsync (null);
4494                 }
4495                 
4496                 [Test]
4497 #if FEATURE_NO_BSD_SOCKETS
4498                 [ExpectedException (typeof (PlatformNotSupportedException))]
4499 #endif
4500                 public void SendAsyncFile ()
4501                 {
4502                         Socket serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4503
4504                         serverSocket.Bind (new IPEndPoint (IPAddress.Loopback, 0));
4505                         serverSocket.Listen (1);
4506
4507                         var mReceived = new ManualResetEvent (false);
4508
4509                         serverSocket.BeginAccept (AsyncCall => {
4510                                 byte[] bytes = new byte [1024];
4511
4512                                 Socket listener = (Socket)AsyncCall.AsyncState;
4513                                 Socket client = listener.EndAccept (AsyncCall);
4514                                 client.Receive (bytes, bytes.Length, 0);
4515                                 client.Close ();
4516                                 mReceived.Set ();
4517                         }, serverSocket);
4518                         
4519                         Socket clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
4520                         clientSocket.Connect (serverSocket.LocalEndPoint);
4521                         clientSocket.NoDelay = true;
4522                                                 
4523                         // Initialize buffer used to create testing file
4524                         var buffer = new byte [1024];
4525                         for (int i = 0; i < 1024; ++i)
4526                                 buffer [i] = (byte) (i % 256);
4527                         
4528                         string temp = Path.GetTempFileName ();
4529                         try {
4530                                 // Testing file creation
4531                                 using (StreamWriter sw = new StreamWriter (temp)) {
4532                                         sw.Write (buffer);
4533                                 }
4534
4535                                 var mSent = new ManualResetEvent (false);
4536
4537                                 // Async Send File to server
4538                                 clientSocket.BeginSendFile(temp, (ar) => {
4539                                         Socket client = (Socket) ar.AsyncState;
4540                                         client.EndSendFile (ar);
4541                                         mSent.Set ();
4542                                 }, clientSocket);
4543
4544                                 if (!mSent.WaitOne (1500))
4545                                         throw new TimeoutException ();
4546                                 if (!mReceived.WaitOne (1500))
4547                                         throw new TimeoutException ();
4548                         } finally {
4549                                 if (File.Exists (temp))
4550                                         File.Delete (temp);
4551                                         
4552                                 clientSocket.Close ();
4553                                 serverSocket.Close ();
4554                         }
4555                 }
4556                 
4557                 [Test]
4558 #if FEATURE_NO_BSD_SOCKETS
4559                 [ExpectedException (typeof (PlatformNotSupportedException))]
4560 #endif
4561                 public void ConnectToIPV4EndPointUsingDualModelSocket () {
4562                         /*
4563                          * IPv6 DualMode sockets are defaults in Mono. Explicitly specify that
4564                          * anyways in this test to make it more interoparable with .NET where
4565                          * IPv6 and DualMode needs to be specified.
4566                          */
4567                         using (var server = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) {
4568
4569                                 var host = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
4570
4571                                 server.DualMode = true;
4572                                 server.Bind (host);
4573                                 /*
4574                                  * Nothing to Accept the connect - we need a backlog to make sure we don't get 
4575                                  Connection refused.
4576                                  */
4577                                 server.Listen (3);
4578                                 
4579                                 var ep = server.LocalEndPoint as IPEndPoint;
4580                                 var client = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
4581                                 client.DualMode = true;
4582                                 client.Connect (ep);
4583                                 client.Disconnect (false);
4584                                 client.Close ();
4585
4586                                 client = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
4587                                 client.DualMode = true;
4588                                 client.Connect (IPAddress.Loopback, ep.Port);
4589                                 client.Disconnect (false);
4590                                 client.Close ();
4591
4592                                 client = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
4593                                 client.DualMode = true;
4594                                 client.Connect (new [] { IPAddress.Loopback }, ep.Port);
4595                                 client.Disconnect (false);
4596                                 client.Close ();
4597                         }
4598                 }
4599                 
4600                 [Test]
4601 #if FEATURE_NO_BSD_SOCKETS
4602                 [ExpectedException (typeof (PlatformNotSupportedException))]
4603 #endif
4604                 public void BeginConnectToIPV4EndPointUsingDualModelSocket () {
4605                         /*
4606                          * IPv6 DualMode sockets are defaults in Mono. Explicitly specify that
4607                          * anyways in this test to make it more interoparable with .NET where
4608                          * IPv6 and DualMode needs to be specified.
4609                          */
4610                         using (var server = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
4611                         {
4612                                 var host = new IPEndPoint (IPAddress.Loopback, NetworkHelpers.FindFreePort ());
4613
4614                                 server.DualMode = true;
4615                                 server.Bind (host);
4616                                 server.Listen (10);
4617                                 
4618                                 var ep = server.LocalEndPoint as IPEndPoint;
4619
4620                                 BCCalledBack.Reset ();
4621                                 var client = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
4622                                 client.DualMode = true;
4623                                 var ar1 = client.BeginConnect (ep, BCCallback, client);
4624                                 Assert.IsTrue (BCCalledBack.WaitOne (10000), "#1");
4625                                 client.Disconnect (false);
4626                                 client.Close ();
4627
4628                                 BCCalledBack.Reset ();
4629                                 client = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
4630                                 client.DualMode = true;
4631                                 var ar2 = client.BeginConnect (IPAddress.Loopback, ep.Port, BCCallback, client);
4632                                 Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2");
4633                                 client.Disconnect (false);
4634                                 client.Close ();
4635
4636                                 BCCalledBack.Reset ();
4637                                 client = new Socket (AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
4638                                 client.DualMode = true;
4639                                 var ar3 = client.BeginConnect (new [] {IPAddress.Loopback}, ep.Port, BCCallback, client);
4640                                 Assert.IsTrue (BCCalledBack.WaitOne (10000), "#2");
4641                                 client.Disconnect (false);
4642                                 client.Close();
4643                         }
4644                 }
4645
4646                 [Test]
4647 #if FEATURE_NO_BSD_SOCKETS
4648                 [ExpectedException (typeof (PlatformNotSupportedException))]
4649 #endif
4650                 public void UdpMulticasTimeToLive ()
4651                 {
4652                         /* see https://bugzilla.xamarin.com/show_bug.cgi?id=36941 */
4653
4654                         using (Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) {
4655                                 IPEndPoint end_point = new IPEndPoint (IPAddress.Any, NetworkHelpers.FindFreePort ());
4656                                 socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1);
4657                                 socket.Bind (end_point);
4658                                 socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 19);
4659                         }
4660                 }
4661
4662                 [Test] // Covers 41616
4663                 public void ConnectAsyncUnhandledEx ()
4664                 {
4665                         var mre = new ManualResetEvent (false);
4666
4667                         var endPoint = new IPEndPoint(0,0);
4668                         var socket = new Socket(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Unspecified);
4669
4670                         var socketArgs = new SocketAsyncEventArgs();
4671                         socketArgs.RemoteEndPoint = endPoint;
4672                         socketArgs.Completed += (sender, e) => mre.Set ();
4673
4674                         socket.ConnectAsync (socketArgs);
4675
4676                         Assert.IsTrue (mre.WaitOne (1000), "ConnectedAsync timeout");
4677                 }
4678
4679                 [Test] // Covers https://bugzilla.xamarin.com/show_bug.cgi?id=52549
4680 #if FEATURE_NO_BSD_SOCKETS
4681                 [ExpectedException (typeof (PlatformNotSupportedException))]
4682 #endif
4683                 public void SocketMismatchProtocol ()
4684                 {
4685                         try {
4686                                 using (Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Tcp));
4687                                 Assert.Fail ("#1");
4688                         } catch (SocketException e) {
4689                                 // Only work on OSX
4690                                 // Assert.AreEqual(SocketError.ProtocolType, e.SocketErrorCode, "#2");
4691                         }
4692
4693                         try {
4694                                 using (Socket socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Udp));
4695                                 Assert.Fail ("#3");
4696                         } catch (SocketException e) {
4697                                 // Only work on OSX
4698                                 // Assert.AreEqual(SocketError.ProtocolType, e.SocketErrorCode, "#4");
4699                         }
4700                 }
4701         }
4702 }
4703