Merge pull request #1304 from slluis/mac-proxy-autoconfig
[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 #if NET_4_5
42 using System.Threading.Tasks;
43 #endif
44
45 namespace System.Net.Sockets
46 {
47         /// <remarks>
48         /// A slightly more abstracted way to listen for incoming
49         /// network connections than a Socket.
50         /// </remarks>
51         public class TcpListener
52         {
53                 // private data
54                 
55                 bool active;
56                 Socket server;
57                 EndPoint savedEP;
58                 
59                 // constructor
60
61                 /// <summary>
62                 /// Some code that is shared between the constructors.
63                 /// </summary>
64                 private void Init (AddressFamily family, EndPoint ep)
65                 {
66                         active = false;
67                         server = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
68                         savedEP = ep;
69                 }
70                 
71                 /// <summary>
72                 /// Constructs a new TcpListener to listen on a specified port
73                 /// </summary>
74                 /// <param name="port">The port to listen on, e.g. 80 if you 
75                 /// are a web server</param>
76                 [Obsolete ("Use TcpListener (IPAddress address, int port) instead")]
77                 public TcpListener (int port)
78                 {
79                         if (port < 0 || port > 65535)
80                                 throw new ArgumentOutOfRangeException ("port");
81
82                         Init (AddressFamily.InterNetwork, new IPEndPoint (IPAddress.Any, port));
83                 }
84
85                 /// <summary>
86                 /// Constructs a new TcpListener with a specified local endpoint
87                 /// </summary>
88                 /// <param name="local_end_point">The endpoint</param>
89                 public TcpListener (IPEndPoint localEP)
90                 {
91                         if (localEP == null)
92                                 throw new ArgumentNullException ("localEP");
93
94                         Init (localEP.AddressFamily, localEP);
95                 }
96                 
97                 /// <summary>
98                 /// Constructs a new TcpListener, listening on a specified port
99                 /// and IP (for use on a multi-homed machine)
100                 /// </summary>
101                 /// <param name="listen_ip">The IP to listen on</param>
102                 /// <param name="port">The port to listen on</param>
103                 public TcpListener (IPAddress localaddr, int port)
104                 {
105                         if (localaddr == null)
106                                 throw new ArgumentNullException ("localaddr");
107
108                         if (port < 0 || port > 65535)
109                                 throw new ArgumentOutOfRangeException ("port");
110
111                         Init (localaddr.AddressFamily, new IPEndPoint (localaddr, port));
112                 }
113
114
115                 // properties
116
117                 /// <summary>
118                 /// A flag that is 'true' if the TcpListener is listening,
119                 /// or 'false' if it is not listening
120                 /// </summary>
121                 protected bool Active
122                 {
123                         get { return active; }
124                 }
125
126                 /// <summary>
127                 /// The local end point
128                 /// </summary>
129                 public EndPoint LocalEndpoint
130                 {
131                         get { 
132                                 if (active)
133                                         return server.LocalEndPoint;
134
135                                 return savedEP; 
136                         }
137                 }
138                 
139                 /// <summary>
140                 /// The listening socket
141                 /// </summary>
142                 public Socket Server
143                 {
144                         get { return server; }
145                 }
146
147                 /// <summary>
148                 /// Specifies whether the TcpListener allows only one
149                 /// underlying socket to listen to a specific port
150                 /// </summary>
151                 public bool ExclusiveAddressUse
152                 {
153                         get {
154                                 if (server == null) {
155                                         throw new ObjectDisposedException (GetType ().ToString ());
156                                 }
157                                 if (active) {
158                                         throw new InvalidOperationException ("The TcpListener has been started");
159                                 }
160
161                                 return(server.ExclusiveAddressUse);
162                         }
163                         set {
164                                 if (server == null) {
165                                         throw new ObjectDisposedException (GetType ().ToString ());
166                                 }
167                                 if (active) {
168                                         throw new InvalidOperationException ("The TcpListener has been started");
169                                 }
170
171                                 server.ExclusiveAddressUse = value;
172                         }
173                 }
174                 
175                 // methods
176
177                 /// <summary>
178                 /// Accepts a pending connection
179                 /// </summary>
180                 /// <returns>A Socket object for the new connection</returns>
181                 public Socket AcceptSocket ()
182                 {
183                         if (!active)
184                                 throw new InvalidOperationException ("Socket is not listening");
185
186                         return server.Accept();
187                 }
188                 
189                 /// <summary>
190                 /// Accepts a pending connection
191                 /// </summary>
192                 /// <returns>A TcpClient
193                 /// object made from the new socket.</returns>
194                 public TcpClient AcceptTcpClient ()
195                 {
196                         if (!active)
197                                 throw new InvalidOperationException ("Socket is not listening");
198
199                         Socket clientSocket = server.Accept ();
200
201                         TcpClient client = new TcpClient(clientSocket);
202                         
203                         return client;
204                 }
205                 
206                 /// <summary>
207                 /// Destructor - stops the listener listening
208                 /// </summary>
209                 ~TcpListener ()
210                 {
211                         if (active)
212                                 Stop();
213                 }
214         
215                 /// <returns>
216                 /// Returns 'true' if there is a connection waiting to be accepted
217                 /// with AcceptSocket() or AcceptTcpClient().
218                 /// </returns>
219                 public bool Pending ()
220                 {
221                         if (!active)
222                                 throw new InvalidOperationException ("Socket is not listening");
223
224                         return server.Poll(0, SelectMode.SelectRead);
225                 }
226                 
227                 /// <summary>
228                 /// Tells the TcpListener to start listening.
229                 /// </summary>
230                 public void Start ()
231                 {
232                         // MS: sets Listen to Int32.MaxValue
233                         this.Start (5);
234                         // According to the man page some BSD and BSD-derived
235                         // systems limit the backlog to 5.  This should really be
236                         // configurable though
237                 }
238
239                 /// <summary>
240                 /// Tells the TcpListener to start listening for max number
241                 /// of pending connections.
242                 /// </summary>
243
244                 public void Start (int backlog)
245                 {
246                         if (active) {
247                                 return;
248                         }
249                         if (server == null) {
250                                 throw new InvalidOperationException ("Invalid server socket");
251                         }
252                         
253                         server.Bind (savedEP);
254                         server.Listen (backlog);
255                         active = true;
256                 }
257
258                 public IAsyncResult BeginAcceptSocket (AsyncCallback callback,
259                                                        object state)
260                 {
261                         if (server == null) {
262                                 throw new ObjectDisposedException (GetType ().ToString ());
263                         }
264                         
265                         return(server.BeginAccept (callback, state));
266                 }
267                 
268                 public IAsyncResult BeginAcceptTcpClient (AsyncCallback callback, object state)
269                 {
270                         if (server == null) {
271                                 throw new ObjectDisposedException (GetType ().ToString ());
272                         }
273                         
274                         return(server.BeginAccept (callback, state));
275                 }
276                 
277                 public Socket EndAcceptSocket (IAsyncResult asyncResult) 
278                 {
279                         return(server.EndAccept (asyncResult));
280                 }
281                 
282                 public TcpClient EndAcceptTcpClient (IAsyncResult asyncResult)
283                 {
284                         Socket clientSocket = server.EndAccept (asyncResult);
285                         TcpClient client = new TcpClient (clientSocket);
286                         
287                         return(client);
288                 }
289                 
290                 /// <summary>
291                 /// Tells the TcpListener to stop listening and dispose
292                 /// of all managed resources.
293                 /// </summary>
294                 public void Stop ()
295                 {
296                         if (active) 
297                         {
298                                 server.Close ();
299                                 server = null;
300                         }
301
302                         Init (AddressFamily.InterNetwork, savedEP);
303                 }
304
305 #if NET_4_5
306                 public Task<Socket> AcceptSocketAsync ()
307                 {
308                         return Task<Socket>.Factory.FromAsync (BeginAcceptSocket, EndAcceptSocket, null);
309                 }
310
311                 public Task<TcpClient> AcceptTcpClientAsync ()
312                 {
313                         return Task<TcpClient>.Factory.FromAsync (BeginAcceptTcpClient, EndAcceptTcpClient, null);
314                 }
315 #endif
316         }
317 }