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
|
//
// System.Net.Sockets.UdpClient.cs
//
// Author:
// Gonzalo Paniagua Javier <gonzalo@ximian.com>
//
// Copyright (C) Ximian, Inc. http://www.ximian.com
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Net;
namespace System.Net.Sockets
{
public class UdpClient : IDisposable
{
private bool disposed = false;
private bool active = false;
private Socket socket;
private AddressFamily family = AddressFamily.InterNetwork;
#region Constructors
public UdpClient () : this(AddressFamily.InterNetwork)
{
}
#if NET_1_1
public UdpClient(AddressFamily family)
{
if(family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
throw new ArgumentException("Family must be InterNetwork or InterNetworkV6", "family");
this.family = family;
InitSocket (null);
}
#endif
public UdpClient (int port)
{
if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
throw new ArgumentOutOfRangeException ("port");
this.family = AddressFamily.InterNetwork;
IPEndPoint localEP = new IPEndPoint (IPAddress.Any, port);
InitSocket (localEP);
}
public UdpClient (IPEndPoint localEP)
{
if (localEP == null)
throw new ArgumentNullException ("localEP");
this.family = localEP.AddressFamily;
InitSocket (localEP);
}
#if NET_1_1
public UdpClient (int port, AddressFamily family)
{
if (family != AddressFamily.InterNetwork &&
family != AddressFamily.InterNetworkV6) {
throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
}
if (port < IPEndPoint.MinPort ||
port > IPEndPoint.MaxPort) {
throw new ArgumentOutOfRangeException ("port");
}
this.family = family;
IPEndPoint localEP = new IPEndPoint (IPAddress.Any, port);
InitSocket (localEP);
}
#endif
public UdpClient (string hostname, int port)
{
if (hostname == null)
throw new ArgumentNullException ("hostname");
if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
throw new ArgumentOutOfRangeException ("port");
InitSocket (null);
Connect (hostname, port);
}
private void InitSocket (EndPoint localEP)
{
if(socket != null) {
socket.Close();
socket = null;
}
socket = new Socket (family, SocketType.Dgram, ProtocolType.Udp);
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
if (localEP != null)
socket.Bind (localEP);
}
#endregion // Constructors
#region Public methods
#region Close
public void Close ()
{
((IDisposable) this).Dispose ();
}
#endregion
#region Connect
public void Connect (IPEndPoint endPoint)
{
CheckDisposed ();
if (endPoint == null)
throw new ArgumentNullException ("endPoint");
socket.Connect (endPoint);
active = true;
}
public void Connect (IPAddress addr, int port)
{
if (addr == null)
throw new ArgumentNullException ("addr");
if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
throw new ArgumentOutOfRangeException ("port");
Connect (new IPEndPoint (addr, port));
}
public void Connect (string hostname, int port)
{
if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
throw new ArgumentOutOfRangeException ("port");
IPAddress[] addresses = Dns.Resolve (hostname).AddressList;
for(int i=0; i<addresses.Length; i++) {
try {
this.family = addresses[i].AddressFamily;
Connect (new IPEndPoint (addresses[i], port));
break;
} catch(Exception e) {
if(i == addresses.Length - 1){
if(socket != null) {
socket.Close();
socket = null;
}
/// This is the last entry, re-throw the exception
throw e;
}
}
}
}
#endregion
#region Multicast methods
public void DropMulticastGroup (IPAddress multicastAddr)
{
CheckDisposed ();
if (multicastAddr == null)
throw new ArgumentNullException ("multicastAddr");
if(family == AddressFamily.InterNetwork)
socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
new MulticastOption (multicastAddr));
#if NET_1_1
else
socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
new IPv6MulticastOption (multicastAddr));
#endif
}
#if NET_1_1
public void DropMulticastGroup (IPAddress multicastAddr,
int ifindex)
{
CheckDisposed ();
/* LAMESPEC: exceptions haven't been specified
* for this overload.
*/
if (multicastAddr == null) {
throw new ArgumentNullException ("multicastAddr");
}
/* Does this overload only apply to IPv6?
* Only the IPv6MulticastOption has an
* ifindex-using constructor. The MS docs
* don't say.
*/
if (family == AddressFamily.InterNetworkV6) {
socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new IPv6MulticastOption (multicastAddr, ifindex));
}
}
#endif
public void JoinMulticastGroup (IPAddress multicastAddr)
{
CheckDisposed ();
if(family == AddressFamily.InterNetwork)
socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
new MulticastOption (multicastAddr));
#if NET_1_1
else
socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
new IPv6MulticastOption (multicastAddr));
#endif
}
#if NET_1_1
public void JoinMulticastGroup (int ifindex,
IPAddress multicastAddr)
{
CheckDisposed ();
/* Does this overload only apply to IPv6?
* Only the IPv6MulticastOption has an
* ifindex-using constructor. The MS docs
* don't say.
*/
if (family == AddressFamily.InterNetworkV6) {
socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption (multicastAddr, ifindex));
}
}
#endif
public void JoinMulticastGroup (IPAddress multicastAddr, int timeToLive)
{
CheckDisposed ();
JoinMulticastGroup (multicastAddr);
if (timeToLive < 0 || timeToLive > 255)
throw new ArgumentOutOfRangeException ("timeToLive");
if(family == AddressFamily.InterNetwork)
socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive,
timeToLive);
#if NET_1_1
else
socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive,
timeToLive);
#endif
}
#endregion
#region Data I/O
public byte [] Receive (ref IPEndPoint remoteEP)
{
CheckDisposed ();
// Bug 45633: the spec states that we should block until a datagram arrives:
// remove the 512 hardcoded value.
// Block until we get it.
socket.Poll (-1, SelectMode.SelectRead);
byte [] recBuffer;
int available = socket.Available;
recBuffer = new byte [available];
EndPoint endPoint = new IPEndPoint (IPAddress.Any, 0);
int dataRead = socket.ReceiveFrom (recBuffer, ref endPoint);
if (dataRead < recBuffer.Length)
recBuffer = CutArray (recBuffer, dataRead);
remoteEP = (IPEndPoint) endPoint;
return recBuffer;
}
public int Send (byte [] dgram, int bytes)
{
CheckDisposed ();
if (dgram == null)
throw new ArgumentNullException ("dgram");
if (!active)
throw new InvalidOperationException ("Operation not allowed on " +
"non-connected sockets.");
return socket.Send (dgram, 0, bytes, SocketFlags.None);
}
public int Send (byte [] dgram, int bytes, IPEndPoint endPoint)
{
CheckDisposed ();
if (dgram == null)
throw new ArgumentNullException ("dgram is null");
if (active) {
if (endPoint != null)
throw new InvalidOperationException ("Cannot send packets to an " +
"arbitrary host while connected.");
return socket.Send (dgram, 0, bytes, SocketFlags.None);
}
return socket.SendTo (dgram, 0, bytes, SocketFlags.None, endPoint);
}
public int Send (byte [] dgram, int bytes, string hostname, int port)
{
return Send (dgram, bytes,
new IPEndPoint (Dns.Resolve (hostname).AddressList [0], port));
}
private byte [] CutArray (byte [] orig, int length)
{
byte [] newArray = new byte [length];
Buffer.BlockCopy (orig, 0, newArray, 0, length);
return newArray;
}
#endregion
#region Properties
protected bool Active {
get { return active; }
set { active = value; }
}
protected Socket Client {
get { return socket; }
set { socket = value; }
}
#endregion
#region Disposing
void IDisposable.Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
void Dispose (bool disposing)
{
if (disposed)
return;
disposed = true;
if (disposing){
if (socket != null)
socket.Close ();
socket = null;
}
}
~UdpClient ()
{
Dispose (false);
}
private void CheckDisposed ()
{
if (disposed)
throw new ObjectDisposedException (GetType().FullName);
}
#endregion
#endregion
}
}
|