forked from kthompson/RtpLib
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UdpListener.cs
446 lines (379 loc) · 15.1 KB
/
UdpListener.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
/*
* Copyright (C) 2009, Kevin Thompson <[email protected]>
* Copyright (C) 2009, Steve Browne <[email protected]>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Git Development Community nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace RtpLib
{
/// <summary>
/// Callback method for handling received data
/// </summary>
/// <param name="listener"></param>
/// <param name="buffer">Data received</param>
/// <returns></returns>
public delegate void DataReceivedHandler(UdpListener listener, UdpBuffer buffer);
public class UdpListener : IDisposable
{
#region Constructors
public UdpListener()
: this(new IPEndPoint(IPAddress.Any, 0))
{
}
public UdpListener(int port)
: this(new IPEndPoint(IPAddress.Any, port))
{
}
public UdpListener(IPEndPoint localEp)
{
Assert.IsNotNull(localEp, "localEp");
this._rwLock = new ReaderWriterLock();
this.BufferSize = UdpBuffer.DefaultBufferSize;
this.LocalEp = new IPEndPoint(localEp.Address, localEp.Port);
this.CreateSocket();
}
~UdpListener()
{
this.Dispose(false);
}
#endregion
#region IDisposable Members
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
public virtual void Dispose(bool disposing)
{
if (disposing)
{
}
if (!this.IsDisposed)
{
this.StopListeningInternal();
this._client = null;
}
}
#endregion
#region Public Methods
/// <summary>
/// Start listening for traffic on the current IPEndPoint
/// </summary>
public void StartListening()
{
try
{
this._rwLock.AcquireWriterLock(Timeout.Infinite);
if (!this.IsStarted)
{
this._client.Bind(this.LocalEp);
this.IsStarted = true;
this.BeginReceive();
}
}
finally
{
this._rwLock.ReleaseWriterLock();
}
}
/// <summary>
/// Stops listening for traffic
/// </summary>
public void StopListening()
{
this.StopListeningInternal();
//recreate socket for reuse
this.CreateSocket();
}
/// <summary>
/// Sends buffered information to a specified IPEndPoint
/// </summary>
/// <param name="buffer"></param>
public void Send(UdpBuffer buffer)
{
this.Send(buffer.Data, 0, buffer.Size, SocketFlags.None, buffer.RemoteEndPoint);
}
/// <summary>
/// Sends buffered information to a specified IPEndPoint
/// </summary>
/// <param name="buffer"></param>
/// <param name="remoteEp"></param>
public void Send(byte[] buffer, EndPoint remoteEp)
{
this.Send(buffer, 0, buffer.Length, SocketFlags.None, remoteEp);
}
/// <summary>
/// Sends buffered information to a specified IPEndPoint
/// </summary>
/// <param name="buffer"></param>
/// <param name="socketFlags"></param>
/// <param name="remoteEp"></param>
public void Send(byte[] buffer, SocketFlags socketFlags, EndPoint remoteEp)
{
this.Send(buffer, 0, buffer.Length, socketFlags, remoteEp);
}
/// <summary>
/// Sends buffered information to a specified IPEndPoint
/// </summary>
/// <param name="buffer"></param>
/// <param name="offset"></param>
/// <param name="size"></param>
/// <param name="socketFlags"></param>
/// <param name="remoteEp"></param>
public void Send(byte[] buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEp)
{
try
{
this._rwLock.AcquireReaderLock(Timeout.Infinite);
if (this.IsStarted)
{
this._client.SendTo(buffer, offset, size, socketFlags, remoteEp);
}
}
finally
{
this._rwLock.ReleaseReaderLock();
}
}
#endregion
#region Multicast Joins
public void JoinMulticastGroup(IPAddress address, int ttl)
{
Assert.AreEqual(address.AddressFamily, this.LocalEp.AddressFamily, "address.AddressFamily");
Assert.That(this.IsStarted, () => new InvalidOperationException("UdpListener must be started to join multicast group"));
switch (this.LocalEp.AddressFamily)
{
case AddressFamily.InterNetwork:
var option1 = new MulticastOption(address, this.LocalEp.Address);
this._client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, option1);
this._client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, ttl);
break;
case AddressFamily.InterNetworkV6:
//FIXME: this should be using the interface index of the interface we are bound to.
var option2 = new IPv6MulticastOption(address);
this._client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, option2);
this._client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive, ttl);
break;
default:
Assert.That(false, () => new NotSupportedException("UdpListener only supports IPv4 and IPv6."));
break;
}
}
public void JoinMulticastGroup(IPAddress address)
{
Assert.That(this.IsStarted, () => new InvalidOperationException("UdpListener must be started to join multicast group"));
Assert.AreEqual(address.AddressFamily, this.LocalEp.AddressFamily, "address.AddressFamily");
switch (this.LocalEp.AddressFamily)
{
case AddressFamily.InterNetwork:
{
var option1 = new MulticastOption(address, this.LocalEp.Address);
this._client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, option1);
}
break;
case AddressFamily.InterNetworkV6:
{
var option2 = new IPv6MulticastOption(address);
this._client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, option2);
}
break;
default:
Assert.That(false,() => new NotSupportedException("UdpListener only supports IPv4 and IPv6."));
break;
}
}
public void DropMulticastGroup(IPAddress address)
{
Assert.AreEqual(address.AddressFamily, this.LocalEp.AddressFamily, "address.AddressFamily");
if (this.LocalEp.AddressFamily == AddressFamily.InterNetwork)
{
var option1 = new MulticastOption(address);
this._client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, option1);
}
else
{
var option2 = new IPv6MulticastOption(address);
this._client.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, option2);
}
}
#endregion
#region Private Helper Methods
private void CreateSocket()
{
this._client = new Socket(this.LocalEp.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
this.ReuseAddress = true;
}
private void StopListeningInternal()
{
try
{
this._rwLock.AcquireWriterLock(Timeout.Infinite);
this.IsStarted = false;
this._client.Close();
}
finally
{
this._rwLock.ReleaseWriterLock();
}
}
protected void BeginReceive()
{
try
{
this._rwLock.AcquireReaderLock(Timeout.Infinite);
if (this.IsStarted)
{
// allocate a packet buffer
var buffer = new UdpBuffer(this.BufferSize);
// kick off an async read
this._client.BeginReceiveFrom(buffer.Data, 0, buffer.Data.Length, SocketFlags.None, ref buffer.RemoteEndPoint, EndReceive, buffer);
}
}
finally
{
this._rwLock.ReleaseReaderLock();
}
}
protected void EndReceive(IAsyncResult async)
{
try
{
this._rwLock.AcquireReaderLock(Timeout.Infinite);
if (this.IsStarted)
{
//immediately start the next receive
this.BeginReceive();
//get the buffer created for this receive
var buffer = (UdpBuffer)async.AsyncState;
//get the data length received
buffer.Size = this._client.EndReceiveFrom(async, ref buffer.RemoteEndPoint);
//fire the callback method
if (this.ReceiveCallback != null)
this.ReceiveCallback(this, buffer);
}
}
catch (SocketException ex)
{
ex.ToString();
}
finally
{
this._rwLock.ReleaseReaderLock();
}
}
#endregion
#region SocketOption Accessors
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue)
{
this._client.SetSocketOption(optionLevel, optionName, optionValue);
}
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
{
this._client.SetSocketOption(optionLevel, optionName, optionValue);
}
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
this._client.SetSocketOption(optionLevel, optionName, optionValue);
}
public object GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName)
{
return this._client.GetSocketOption(optionLevel, optionName);
}
public byte[] GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionLength)
{
return this._client.GetSocketOption(optionLevel, optionName, optionLength);
}
public void GetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, byte[] optionValue)
{
this._client.GetSocketOption(optionLevel, optionName, optionValue);
}
#endregion
#region Properties
private readonly ReaderWriterLock _rwLock;
private Socket _client;
public bool IsDisposed
{
get { return (this._client == null); }
}
public IPEndPoint LocalEp { get; private set; }
public bool IsStarted { get; private set; }
public int BufferSize { get; set; }
public DataReceivedHandler ReceiveCallback { get; set; }
public short Ttl
{
get
{
return (short)this._client.GetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive);
}
set
{
this._client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, value);
}
}
public bool EnableBroadcast
{
get
{
return (((int)this._client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast)) != 0);
}
set
{
this._client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, value ? 1 : 0);
}
}
public bool ReuseAddress
{
get
{
return ((int)this._client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress) == 1);
}
set
{
this._client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, (value ? 1 : 0));
}
}
public int ReceiveBuffer
{
get { return (int)this._client.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer); }
set { this._client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value); }
}
#endregion
}
}