Merge pull request #3750 from marek-safar/socket
[mono-project.git] / mcs / class / System / System.Net.Sockets / TcpListener.cs
blobe8b8ec40e0e2e9cdfd183205647328730cbdec8b
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)
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:
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.
39 using System;
40 using System.Net;
41 using System.Threading.Tasks;
43 namespace System.Net.Sockets
45 /// <remarks>
46 /// A slightly more abstracted way to listen for incoming
47 /// network connections than a Socket.
48 /// </remarks>
49 public class TcpListener
51 // private data
53 bool active;
54 Socket server;
55 EndPoint savedEP;
57 // constructor
59 /// <summary>
60 /// Some code that is shared between the constructors.
61 /// </summary>
62 private void Init (AddressFamily family, EndPoint ep)
64 active = false;
65 server = new Socket(family, SocketType.Stream, ProtocolType.Tcp);
66 savedEP = ep;
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)
77 if (port < 0 || port > 65535)
78 throw new ArgumentOutOfRangeException ("port");
80 Init (AddressFamily.InterNetwork, new IPEndPoint (IPAddress.Any, port));
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)
89 if (localEP == null)
90 throw new ArgumentNullException ("localEP");
92 Init (localEP.AddressFamily, localEP);
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)
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));
113 // properties
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
121 get { return active; }
124 /// <summary>
125 /// The local end point
126 /// </summary>
127 public EndPoint LocalEndpoint
129 get {
130 if (active)
131 return server.LocalEndPoint;
133 return savedEP;
137 /// <summary>
138 /// The listening socket
139 /// </summary>
140 public Socket Server
142 get { return server; }
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
151 get {
152 if (server == null) {
153 throw new ObjectDisposedException (GetType ().ToString ());
155 if (active) {
156 throw new InvalidOperationException ("The TcpListener has been started");
159 return(server.ExclusiveAddressUse);
161 set {
162 if (server == null) {
163 throw new ObjectDisposedException (GetType ().ToString ());
165 if (active) {
166 throw new InvalidOperationException ("The TcpListener has been started");
169 server.ExclusiveAddressUse = value;
173 // methods
175 /// <summary>
176 /// Accepts a pending connection
177 /// </summary>
178 /// <returns>A Socket object for the new connection</returns>
179 public Socket AcceptSocket ()
181 if (!active)
182 throw new InvalidOperationException ("Socket is not listening");
184 return server.Accept();
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 ()
194 if (!active)
195 throw new InvalidOperationException ("Socket is not listening");
197 Socket clientSocket = server.Accept ();
199 TcpClient client = new TcpClient(clientSocket);
201 return client;
204 public void AllowNatTraversal (bool allowed)
206 if (active)
207 throw new InvalidOperationException (SR.GetString (SR.net_tcplistener_mustbestopped));
209 if (allowed)
210 server.SetIPProtectionLevel (IPProtectionLevel.Unrestricted);
211 else
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;
223 return listener;
226 /// <summary>
227 /// Destructor - stops the listener listening
228 /// </summary>
229 ~TcpListener ()
231 if (active)
232 Stop();
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 ()
241 if (!active)
242 throw new InvalidOperationException ("Socket is not listening");
244 return server.Poll(0, SelectMode.SelectRead);
247 /// <summary>
248 /// Tells the TcpListener to start listening.
249 /// </summary>
250 public void Start ()
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
259 /// <summary>
260 /// Tells the TcpListener to start listening for max number
261 /// of pending connections.
262 /// </summary>
264 public void Start (int backlog)
266 if (active) {
267 return;
269 if (server == null) {
270 throw new InvalidOperationException ("Invalid server socket");
273 server.Bind (savedEP);
274 server.Listen (backlog);
275 active = true;
278 public IAsyncResult BeginAcceptSocket (AsyncCallback callback,
279 object state)
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);
307 return(client);
310 /// <summary>
311 /// Tells the TcpListener to stop listening and dispose
312 /// of all managed resources.
313 /// </summary>
314 public void Stop ()
316 if (active)
318 server.Close ();
319 server = null;
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);