4 // Phillip Pearson (pp@myelin.co.nz)
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // Sridhar Kulkarni (sridharkulkarni@gmail.com)
8 // Marek Safar (marek.safar@gmail.com)
11 // Copyright (C) 2001, Phillip Pearson http://www.myelin.co.nz
13 // (c) 2003 Ximian, Inc. (http://www.ximian.com)
14 // (c) 2004-2006 Novell, Inc.
15 // Copyright 2011 Xamarin Inc.
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:
27 // The above copyright notice and this permission notice shall be
28 // included in all copies or substantial portions of the Software.
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.
42 using System.Threading.Tasks;
45 namespace System.Net.Sockets
48 /// A slightly more abstracted way to listen for incoming
49 /// network connections than a Socket.
51 public class TcpListener
62 /// Some code that is shared between the constructors.
64 private void Init (AddressFamily family, EndPoint ep)
67 server = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
72 /// Constructs a new TcpListener to listen on a specified port
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)
79 if (port < 0 || port > 65535)
80 throw new ArgumentOutOfRangeException ("port");
82 Init (AddressFamily.InterNetwork, new IPEndPoint (IPAddress.Any, port));
86 /// Constructs a new TcpListener with a specified local endpoint
88 /// <param name="local_end_point">The endpoint</param>
89 public TcpListener (IPEndPoint localEP)
92 throw new ArgumentNullException ("localEP");
94 Init (localEP.AddressFamily, localEP);
98 /// Constructs a new TcpListener, listening on a specified port
99 /// and IP (for use on a multi-homed machine)
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)
105 if (localaddr == null)
106 throw new ArgumentNullException ("localaddr");
108 if (port < 0 || port > 65535)
109 throw new ArgumentOutOfRangeException ("port");
111 Init (localaddr.AddressFamily, new IPEndPoint (localaddr, port));
118 /// A flag that is 'true' if the TcpListener is listening,
119 /// or 'false' if it is not listening
121 protected bool Active
123 get { return active; }
127 /// The local end point
129 public EndPoint LocalEndpoint
133 return server.LocalEndPoint;
140 /// The listening socket
144 get { return server; }
148 /// Specifies whether the TcpListener allows only one
149 /// underlying socket to listen to a specific port
152 [MonoNotSupported ("Not supported as Socket.ExclusiveAddressUse is not supported")]
154 public bool ExclusiveAddressUse
157 if (server == null) {
158 throw new ObjectDisposedException (GetType ().ToString ());
161 throw new InvalidOperationException ("The TcpListener has been started");
164 return(server.ExclusiveAddressUse);
167 if (server == null) {
168 throw new ObjectDisposedException (GetType ().ToString ());
171 throw new InvalidOperationException ("The TcpListener has been started");
174 server.ExclusiveAddressUse = value;
181 /// Accepts a pending connection
183 /// <returns>A Socket object for the new connection</returns>
184 public Socket AcceptSocket ()
187 throw new InvalidOperationException ("Socket is not listening");
189 return server.Accept();
193 /// Accepts a pending connection
195 /// <returns>A TcpClient
196 /// object made from the new socket.</returns>
197 public TcpClient AcceptTcpClient ()
200 throw new InvalidOperationException ("Socket is not listening");
202 Socket clientSocket = server.Accept ();
204 TcpClient client = new TcpClient(clientSocket);
210 /// Destructor - stops the listener listening
219 /// Returns 'true' if there is a connection waiting to be accepted
220 /// with AcceptSocket() or AcceptTcpClient().
222 public bool Pending ()
225 throw new InvalidOperationException ("Socket is not listening");
227 return server.Poll(0, SelectMode.SelectRead);
231 /// Tells the TcpListener to start listening.
235 // MS: sets Listen to Int32.MaxValue
237 // According to the man page some BSD and BSD-derived
238 // systems limit the backlog to 5. This should really be
239 // configurable though
243 /// Tells the TcpListener to start listening for max number
244 /// of pending connections.
247 public void Start (int backlog)
252 if (server == null) {
253 throw new InvalidOperationException ("Invalid server socket");
256 server.Bind (savedEP);
257 server.Listen (backlog);
261 public IAsyncResult BeginAcceptSocket (AsyncCallback callback,
264 if (server == null) {
265 throw new ObjectDisposedException (GetType ().ToString ());
268 return(server.BeginAccept (callback, state));
271 public IAsyncResult BeginAcceptTcpClient (AsyncCallback callback, object state)
273 if (server == null) {
274 throw new ObjectDisposedException (GetType ().ToString ());
277 return(server.BeginAccept (callback, state));
280 public Socket EndAcceptSocket (IAsyncResult asyncResult)
282 return(server.EndAccept (asyncResult));
285 public TcpClient EndAcceptTcpClient (IAsyncResult asyncResult)
287 Socket clientSocket = server.EndAccept (asyncResult);
288 TcpClient client = new TcpClient (clientSocket);
294 /// Tells the TcpListener to stop listening and dispose
295 /// of all managed resources.
305 Init (AddressFamily.InterNetwork, savedEP);
309 public Task<Socket> AcceptSocketAsync ()
311 return Task<Socket>.Factory.FromAsync (BeginAcceptSocket, EndAcceptSocket, null);
314 public Task<TcpClient> AcceptTcpClientAsync ()
316 return Task<TcpClient>.Factory.FromAsync (BeginAcceptTcpClient, EndAcceptTcpClient, null);