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