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.
41 using System.Threading.Tasks;
43 namespace System.Net.Sockets
46 /// A slightly more abstracted way to listen for incoming
47 /// network connections than a Socket.
49 public class TcpListener
60 /// Some code that is shared between the constructors.
62 private void Init (AddressFamily family, EndPoint ep)
65 server = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
70 /// Constructs a new TcpListener to listen on a specified port
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)
77 if (port < 0 || port > 65535)
78 throw new ArgumentOutOfRangeException ("port");
80 Init (AddressFamily.InterNetwork, new IPEndPoint (IPAddress.Any, port));
84 /// Constructs a new TcpListener with a specified local endpoint
86 /// <param name="local_end_point">The endpoint</param>
87 public TcpListener (IPEndPoint localEP)
90 throw new ArgumentNullException ("localEP");
92 Init (localEP.AddressFamily, localEP);
96 /// Constructs a new TcpListener, listening on a specified port
97 /// and IP (for use on a multi-homed machine)
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)
103 if (localaddr == null)
104 throw new ArgumentNullException ("localaddr");
106 if (port < 0 || port > 65535)
107 throw new ArgumentOutOfRangeException ("port");
109 Init (localaddr.AddressFamily, new IPEndPoint (localaddr, port));
116 /// A flag that is 'true' if the TcpListener is listening,
117 /// or 'false' if it is not listening
119 protected bool Active
121 get { return active; }
125 /// The local end point
127 public EndPoint LocalEndpoint
131 return server.LocalEndPoint;
138 /// The listening socket
142 get { return server; }
146 /// Specifies whether the TcpListener allows only one
147 /// underlying socket to listen to a specific port
149 public bool ExclusiveAddressUse
152 if (server == null) {
153 throw new ObjectDisposedException (GetType ().ToString ());
156 throw new InvalidOperationException ("The TcpListener has been started");
159 return(server.ExclusiveAddressUse);
162 if (server == null) {
163 throw new ObjectDisposedException (GetType ().ToString ());
166 throw new InvalidOperationException ("The TcpListener has been started");
169 server.ExclusiveAddressUse = value;
176 /// Accepts a pending connection
178 /// <returns>A Socket object for the new connection</returns>
179 public Socket AcceptSocket ()
182 throw new InvalidOperationException ("Socket is not listening");
184 return server.Accept();
188 /// Accepts a pending connection
190 /// <returns>A TcpClient
191 /// object made from the new socket.</returns>
192 public TcpClient AcceptTcpClient ()
195 throw new InvalidOperationException ("Socket is not listening");
197 Socket clientSocket = server.Accept ();
199 TcpClient client = new TcpClient(clientSocket);
204 public void AllowNatTraversal (bool allowed)
207 throw new InvalidOperationException (SR.GetString (SR.net_tcplistener_mustbestopped));
210 server.SetIPProtectionLevel (IPProtectionLevel.Unrestricted);
212 server.SetIPProtectionLevel (IPProtectionLevel.EdgeRestricted);
215 public static TcpListener Create (int port)
217 if (port < 0 || port > 65535)
218 throw new ArgumentOutOfRangeException ("port");
220 TcpListener listener = new TcpListener (IPAddress.IPv6Any, port);
221 listener.Server.DualMode = true;
227 /// Destructor - stops the listener listening
236 /// Returns 'true' if there is a connection waiting to be accepted
237 /// with AcceptSocket() or AcceptTcpClient().
239 public bool Pending ()
242 throw new InvalidOperationException ("Socket is not listening");
244 return server.Poll(0, SelectMode.SelectRead);
248 /// Tells the TcpListener to start listening.
252 // MS: sets Listen to Int32.MaxValue
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
260 /// Tells the TcpListener to start listening for max number
261 /// of pending connections.
264 public void Start (int backlog)
269 if (server == null) {
270 throw new InvalidOperationException ("Invalid server socket");
273 server.Bind (savedEP);
274 server.Listen (backlog);
278 public IAsyncResult BeginAcceptSocket (AsyncCallback callback,
281 if (server == null) {
282 throw new ObjectDisposedException (GetType ().ToString ());
285 return(server.BeginAccept (callback, state));
288 public IAsyncResult BeginAcceptTcpClient (AsyncCallback callback, object state)
290 if (server == null) {
291 throw new ObjectDisposedException (GetType ().ToString ());
294 return(server.BeginAccept (callback, state));
297 public Socket EndAcceptSocket (IAsyncResult asyncResult)
299 return(server.EndAccept (asyncResult));
302 public TcpClient EndAcceptTcpClient (IAsyncResult asyncResult)
304 Socket clientSocket = server.EndAccept (asyncResult);
305 TcpClient client = new TcpClient (clientSocket);
311 /// Tells the TcpListener to stop listening and dispose
312 /// of all managed resources.
322 Init (AddressFamily.InterNetwork, savedEP);
325 public Task<Socket> AcceptSocketAsync ()
327 return Task<Socket>.Factory.FromAsync (BeginAcceptSocket, EndAcceptSocket, null);
330 public Task<TcpClient> AcceptTcpClientAsync ()
332 return Task<TcpClient>.Factory.FromAsync (BeginAcceptTcpClient, EndAcceptTcpClient, null);