Merge pull request #3647 from BrzVlad/fix-sgen-internal-alloc
[mono.git] / mcs / class / System / System.Net.Sockets / TcpListener.cs
1 // TcpListener.cs
2 //
3 // Authors:
4 //    Phillip Pearson (pp@myelin.co.nz)
5 //    Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //        Patrik Torstensson
7 //    Sridhar Kulkarni (sridharkulkarni@gmail.com)
8 //    Marek Safar (marek.safar@gmail.com)
9
10 //
11 // Copyright (C) 2001, Phillip Pearson http://www.myelin.co.nz
12 //
13 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
14 // (c) 2004-2006 Novell, Inc.
15 // Copyright 2011 Xamarin Inc.
16 //
17
18 //
19 // Permission is hereby granted, free of charge, to any person obtaining
20 // a copy of this software and associated documentation files (the
21 // "Software"), to deal in the Software without restriction, including
22 // without limitation the rights to use, copy, modify, merge, publish,
23 // distribute, sublicense, and/or sell copies of the Software, and to
24 // permit persons to whom the Software is furnished to do so, subject to
25 // the following conditions:
26 // 
27 // The above copyright notice and this permission notice shall be
28 // included in all copies or substantial portions of the Software.
29 // 
30 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
31 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
32 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
33 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
34 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
35 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
36 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 //
38
39 using System;
40 using System.Net;
41 using System.Threading.Tasks;
42
43 namespace System.Net.Sockets
44 {
45         /// <remarks>
46         /// A slightly more abstracted way to listen for incoming
47         /// network connections than a Socket.
48         /// </remarks>
49         public class TcpListener
50         {
51                 // private data
52                 
53                 bool active;
54                 Socket server;
55                 EndPoint savedEP;
56                 
57                 // constructor
58
59                 /// <summary>
60                 /// Some code that is shared between the constructors.
61                 /// </summary>
62                 private void Init (AddressFamily family, EndPoint ep)
63                 {
64                         active = false;
65                         server = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
66                         savedEP = ep;
67                 }
68                 
69                 /// <summary>
70                 /// Constructs a new TcpListener to listen on a specified port
71                 /// </summary>
72                 /// <param name="port">The port to listen on, e.g. 80 if you 
73                 /// are a web server</param>
74                 [Obsolete ("Use TcpListener (IPAddress address, int port) instead")]
75                 public TcpListener (int port)
76                 {
77                         if (port < 0 || port > 65535)
78                                 throw new ArgumentOutOfRangeException ("port");
79
80                         Init (AddressFamily.InterNetwork, new IPEndPoint (IPAddress.Any, port));
81                 }
82
83                 /// <summary>
84                 /// Constructs a new TcpListener with a specified local endpoint
85                 /// </summary>
86                 /// <param name="local_end_point">The endpoint</param>
87                 public TcpListener (IPEndPoint localEP)
88                 {
89                         if (localEP == null)
90                                 throw new ArgumentNullException ("localEP");
91
92                         Init (localEP.AddressFamily, localEP);
93                 }
94                 
95                 /// <summary>
96                 /// Constructs a new TcpListener, listening on a specified port
97                 /// and IP (for use on a multi-homed machine)
98                 /// </summary>
99                 /// <param name="listen_ip">The IP to listen on</param>
100                 /// <param name="port">The port to listen on</param>
101                 public TcpListener (IPAddress localaddr, int port)
102                 {
103                         if (localaddr == null)
104                                 throw new ArgumentNullException ("localaddr");
105
106                         if (port < 0 || port > 65535)
107                                 throw new ArgumentOutOfRangeException ("port");
108
109                         Init (localaddr.AddressFamily, new IPEndPoint (localaddr, port));
110                 }
111
112
113                 // properties
114
115                 /// <summary>
116                 /// A flag that is 'true' if the TcpListener is listening,
117                 /// or 'false' if it is not listening
118                 /// </summary>
119                 protected bool Active
120                 {
121                         get { return active; }
122                 }
123
124                 /// <summary>
125                 /// The local end point
126                 /// </summary>
127                 public EndPoint LocalEndpoint
128                 {
129                         get { 
130                                 if (active)
131                                         return server.LocalEndPoint;
132
133                                 return savedEP; 
134                         }
135                 }
136                 
137                 /// <summary>
138                 /// The listening socket
139                 /// </summary>
140                 public Socket Server
141                 {
142                         get { return server; }
143                 }
144
145                 /// <summary>
146                 /// Specifies whether the TcpListener allows only one
147                 /// underlying socket to listen to a specific port
148                 /// </summary>
149                 public bool ExclusiveAddressUse
150                 {
151                         get {
152                                 if (server == null) {
153                                         throw new ObjectDisposedException (GetType ().ToString ());
154                                 }
155                                 if (active) {
156                                         throw new InvalidOperationException ("The TcpListener has been started");
157                                 }
158
159                                 return(server.ExclusiveAddressUse);
160                         }
161                         set {
162                                 if (server == null) {
163                                         throw new ObjectDisposedException (GetType ().ToString ());
164                                 }
165                                 if (active) {
166                                         throw new InvalidOperationException ("The TcpListener has been started");
167                                 }
168
169                                 server.ExclusiveAddressUse = value;
170                         }
171                 }
172                 
173                 // methods
174
175                 /// <summary>
176                 /// Accepts a pending connection
177                 /// </summary>
178                 /// <returns>A Socket object for the new connection</returns>
179                 public Socket AcceptSocket ()
180                 {
181                         if (!active)
182                                 throw new InvalidOperationException ("Socket is not listening");
183
184                         return server.Accept();
185                 }
186                 
187                 /// <summary>
188                 /// Accepts a pending connection
189                 /// </summary>
190                 /// <returns>A TcpClient
191                 /// object made from the new socket.</returns>
192                 public TcpClient AcceptTcpClient ()
193                 {
194                         if (!active)
195                                 throw new InvalidOperationException ("Socket is not listening");
196
197                         Socket clientSocket = server.Accept ();
198
199                         TcpClient client = new TcpClient(clientSocket);
200                         
201                         return client;
202                 }
203
204                 public void AllowNatTraversal (bool allowed)
205                 {
206                         if (active)
207                                 throw new InvalidOperationException (SR.GetString (SR.net_tcplistener_mustbestopped));
208
209                         if (allowed)
210                                 server.SetIPProtectionLevel (IPProtectionLevel.Unrestricted);
211                         else
212                                 server.SetIPProtectionLevel (IPProtectionLevel.EdgeRestricted);
213                 }
214
215                 public static TcpListener Create (int port)
216                 {
217                         if (port < 0 || port > 65535)
218                                 throw new ArgumentOutOfRangeException ("port");
219
220                         TcpListener listener = new TcpListener (IPAddress.IPv6Any, port);
221                         listener.Server.DualMode = true;
222
223                         return listener;
224                 }
225
226                 /// <summary>
227                 /// Destructor - stops the listener listening
228                 /// </summary>
229                 ~TcpListener ()
230                 {
231                         if (active)
232                                 Stop();
233                 }
234         
235                 /// <returns>
236                 /// Returns 'true' if there is a connection waiting to be accepted
237                 /// with AcceptSocket() or AcceptTcpClient().
238                 /// </returns>
239                 public bool Pending ()
240                 {
241                         if (!active)
242                                 throw new InvalidOperationException ("Socket is not listening");
243
244                         return server.Poll(0, SelectMode.SelectRead);
245                 }
246                 
247                 /// <summary>
248                 /// Tells the TcpListener to start listening.
249                 /// </summary>
250                 public void Start ()
251                 {
252                         // MS: sets Listen to Int32.MaxValue
253                         this.Start (5);
254                         // According to the man page some BSD and BSD-derived
255                         // systems limit the backlog to 5.  This should really be
256                         // configurable though
257                 }
258
259                 /// <summary>
260                 /// Tells the TcpListener to start listening for max number
261                 /// of pending connections.
262                 /// </summary>
263
264                 public void Start (int backlog)
265                 {
266                         if (active) {
267                                 return;
268                         }
269                         if (server == null) {
270                                 throw new InvalidOperationException ("Invalid server socket");
271                         }
272                         
273                         server.Bind (savedEP);
274                         server.Listen (backlog);
275                         active = true;
276                 }
277
278                 public IAsyncResult BeginAcceptSocket (AsyncCallback callback,
279                                                        object state)
280                 {
281                         if (server == null) {
282                                 throw new ObjectDisposedException (GetType ().ToString ());
283                         }
284                         
285                         return(server.BeginAccept (callback, state));
286                 }
287                 
288                 public IAsyncResult BeginAcceptTcpClient (AsyncCallback callback, object state)
289                 {
290                         if (server == null) {
291                                 throw new ObjectDisposedException (GetType ().ToString ());
292                         }
293                         
294                         return(server.BeginAccept (callback, state));
295                 }
296                 
297                 public Socket EndAcceptSocket (IAsyncResult asyncResult) 
298                 {
299                         return(server.EndAccept (asyncResult));
300                 }
301                 
302                 public TcpClient EndAcceptTcpClient (IAsyncResult asyncResult)
303                 {
304                         Socket clientSocket = server.EndAccept (asyncResult);
305                         TcpClient client = new TcpClient (clientSocket);
306                         
307                         return(client);
308                 }
309                 
310                 /// <summary>
311                 /// Tells the TcpListener to stop listening and dispose
312                 /// of all managed resources.
313                 /// </summary>
314                 public void Stop ()
315                 {
316                         if (active) 
317                         {
318                                 server.Close ();
319                                 server = null;
320                         }
321
322                         Init (AddressFamily.InterNetwork, savedEP);
323                 }
324
325                 public Task<Socket> AcceptSocketAsync ()
326                 {
327                         return Task<Socket>.Factory.FromAsync (BeginAcceptSocket, EndAcceptSocket, null);
328                 }
329
330                 public Task<TcpClient> AcceptTcpClientAsync ()
331                 {
332                         return Task<TcpClient>.Factory.FromAsync (BeginAcceptTcpClient, EndAcceptTcpClient, null);
333                 }
334         }
335 }