UdpClient.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. //
  2. // System.Net.Sockets.UdpClient.cs
  3. //
  4. // Author:
  5. // Gonzalo Paniagua Javier <[email protected]>
  6. // Sridhar Kulkarni ([email protected])
  7. //
  8. // Copyright (C) Ximian, Inc. http://www.ximian.com
  9. //
  10. //
  11. // Permission is hereby granted, free of charge, to any person obtaining
  12. // a copy of this software and associated documentation files (the
  13. // "Software"), to deal in the Software without restriction, including
  14. // without limitation the rights to use, copy, modify, merge, publish,
  15. // distribute, sublicense, and/or sell copies of the Software, and to
  16. // permit persons to whom the Software is furnished to do so, subject to
  17. // the following conditions:
  18. //
  19. // The above copyright notice and this permission notice shall be
  20. // included in all copies or substantial portions of the Software.
  21. //
  22. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  23. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  24. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  25. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  26. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  27. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  28. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  29. //
  30. using System;
  31. using System.Net;
  32. namespace System.Net.Sockets
  33. {
  34. public class UdpClient : IDisposable
  35. {
  36. private bool disposed = false;
  37. private bool active = false;
  38. private Socket socket;
  39. private AddressFamily family = AddressFamily.InterNetwork;
  40. #if NET_2_0
  41. private byte[] recvbuffer;
  42. #endif
  43. #region Constructors
  44. public UdpClient () : this(AddressFamily.InterNetwork)
  45. {
  46. }
  47. #if NET_1_1
  48. public UdpClient(AddressFamily family)
  49. {
  50. if(family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
  51. throw new ArgumentException("Family must be InterNetwork or InterNetworkV6", "family");
  52. this.family = family;
  53. InitSocket (null);
  54. }
  55. #endif
  56. public UdpClient (int port)
  57. {
  58. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  59. throw new ArgumentOutOfRangeException ("port");
  60. this.family = AddressFamily.InterNetwork;
  61. IPEndPoint localEP = new IPEndPoint (IPAddress.Any, port);
  62. InitSocket (localEP);
  63. }
  64. public UdpClient (IPEndPoint localEP)
  65. {
  66. if (localEP == null)
  67. throw new ArgumentNullException ("localEP");
  68. this.family = localEP.AddressFamily;
  69. InitSocket (localEP);
  70. }
  71. #if NET_1_1
  72. public UdpClient (int port, AddressFamily family)
  73. {
  74. if (family != AddressFamily.InterNetwork &&
  75. family != AddressFamily.InterNetworkV6) {
  76. throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
  77. }
  78. if (port < IPEndPoint.MinPort ||
  79. port > IPEndPoint.MaxPort) {
  80. throw new ArgumentOutOfRangeException ("port");
  81. }
  82. this.family = family;
  83. IPEndPoint localEP = new IPEndPoint (IPAddress.Any, port);
  84. InitSocket (localEP);
  85. }
  86. #endif
  87. public UdpClient (string hostname, int port)
  88. {
  89. if (hostname == null)
  90. throw new ArgumentNullException ("hostname");
  91. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  92. throw new ArgumentOutOfRangeException ("port");
  93. InitSocket (null);
  94. Connect (hostname, port);
  95. }
  96. private void InitSocket (EndPoint localEP)
  97. {
  98. if(socket != null) {
  99. socket.Close();
  100. socket = null;
  101. }
  102. socket = new Socket (family, SocketType.Dgram, ProtocolType.Udp);
  103. if (localEP != null)
  104. socket.Bind (localEP);
  105. }
  106. #endregion // Constructors
  107. #region Public methods
  108. #region Close
  109. public void Close ()
  110. {
  111. ((IDisposable) this).Dispose ();
  112. }
  113. #endregion
  114. #region Connect
  115. void DoConnect (IPEndPoint endPoint)
  116. {
  117. /* Catch EACCES and turn on SO_BROADCAST then,
  118. * as UDP sockets don't have it set by default
  119. */
  120. try {
  121. socket.Connect (endPoint);
  122. } catch (SocketException ex) {
  123. if (ex.ErrorCode == (int)SocketError.AccessDenied) {
  124. socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  125. socket.Connect (endPoint);
  126. } else {
  127. throw;
  128. }
  129. }
  130. }
  131. public void Connect (IPEndPoint endPoint)
  132. {
  133. CheckDisposed ();
  134. if (endPoint == null)
  135. throw new ArgumentNullException ("endPoint");
  136. DoConnect (endPoint);
  137. active = true;
  138. }
  139. public void Connect (IPAddress addr, int port)
  140. {
  141. if (addr == null)
  142. throw new ArgumentNullException ("addr");
  143. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  144. throw new ArgumentOutOfRangeException ("port");
  145. Connect (new IPEndPoint (addr, port));
  146. }
  147. public void Connect (string hostname, int port)
  148. {
  149. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  150. throw new ArgumentOutOfRangeException ("port");
  151. IPAddress[] addresses = Dns.Resolve (hostname).AddressList;
  152. for(int i=0; i<addresses.Length; i++) {
  153. try {
  154. this.family = addresses[i].AddressFamily;
  155. Connect (new IPEndPoint (addresses[i], port));
  156. break;
  157. } catch(Exception e) {
  158. if(i == addresses.Length - 1){
  159. if(socket != null) {
  160. socket.Close();
  161. socket = null;
  162. }
  163. /// This is the last entry, re-throw the exception
  164. throw e;
  165. }
  166. }
  167. }
  168. }
  169. #endregion
  170. #region Multicast methods
  171. public void DropMulticastGroup (IPAddress multicastAddr)
  172. {
  173. CheckDisposed ();
  174. if (multicastAddr == null)
  175. throw new ArgumentNullException ("multicastAddr");
  176. if(family == AddressFamily.InterNetwork)
  177. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
  178. new MulticastOption (multicastAddr));
  179. #if NET_1_1
  180. else
  181. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
  182. new IPv6MulticastOption (multicastAddr));
  183. #endif
  184. }
  185. #if NET_1_1
  186. public void DropMulticastGroup (IPAddress multicastAddr,
  187. int ifindex)
  188. {
  189. CheckDisposed ();
  190. /* LAMESPEC: exceptions haven't been specified
  191. * for this overload.
  192. */
  193. if (multicastAddr == null) {
  194. throw new ArgumentNullException ("multicastAddr");
  195. }
  196. /* Does this overload only apply to IPv6?
  197. * Only the IPv6MulticastOption has an
  198. * ifindex-using constructor. The MS docs
  199. * don't say.
  200. */
  201. if (family == AddressFamily.InterNetworkV6) {
  202. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new IPv6MulticastOption (multicastAddr, ifindex));
  203. }
  204. }
  205. #endif
  206. public void JoinMulticastGroup (IPAddress multicastAddr)
  207. {
  208. CheckDisposed ();
  209. if(family == AddressFamily.InterNetwork)
  210. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
  211. new MulticastOption (multicastAddr));
  212. #if NET_1_1
  213. else
  214. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
  215. new IPv6MulticastOption (multicastAddr));
  216. #endif
  217. }
  218. #if NET_1_1
  219. public void JoinMulticastGroup (int ifindex,
  220. IPAddress multicastAddr)
  221. {
  222. CheckDisposed ();
  223. /* Does this overload only apply to IPv6?
  224. * Only the IPv6MulticastOption has an
  225. * ifindex-using constructor. The MS docs
  226. * don't say.
  227. */
  228. if (family == AddressFamily.InterNetworkV6) {
  229. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption (multicastAddr, ifindex));
  230. }
  231. }
  232. #endif
  233. public void JoinMulticastGroup (IPAddress multicastAddr, int timeToLive)
  234. {
  235. CheckDisposed ();
  236. JoinMulticastGroup (multicastAddr);
  237. if (timeToLive < 0 || timeToLive > 255)
  238. throw new ArgumentOutOfRangeException ("timeToLive");
  239. if(family == AddressFamily.InterNetwork)
  240. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive,
  241. timeToLive);
  242. #if NET_1_1
  243. else
  244. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive,
  245. timeToLive);
  246. #endif
  247. }
  248. #if NET_2_0
  249. public void JoinMulticastGroup (IPAddress multicastAddr,
  250. IPAddress localAddress)
  251. {
  252. CheckDisposed ();
  253. JoinMulticastGroup (multicastAddr);
  254. if (family == AddressFamily.InterNetwork) {
  255. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption (multicastAddr, localAddress));
  256. } else if (family == AddressFamily.InterNetworkV6) {
  257. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new MulticastOption (multicastAddr, localAddress));
  258. }
  259. }
  260. #endif
  261. #endregion
  262. #region Data I/O
  263. public byte [] Receive (ref IPEndPoint remoteEP)
  264. {
  265. CheckDisposed ();
  266. // Bug 45633: the spec states that we should block until a datagram arrives:
  267. // remove the 512 hardcoded value.
  268. // Block until we get it.
  269. socket.Poll (-1, SelectMode.SelectRead);
  270. byte [] recBuffer;
  271. int available = socket.Available;
  272. recBuffer = new byte [available];
  273. EndPoint endPoint = new IPEndPoint (IPAddress.Any, 0);
  274. int dataRead = socket.ReceiveFrom (recBuffer, ref endPoint);
  275. if (dataRead < recBuffer.Length)
  276. recBuffer = CutArray (recBuffer, dataRead);
  277. remoteEP = (IPEndPoint) endPoint;
  278. return recBuffer;
  279. }
  280. int DoSend (byte[] dgram, int bytes, IPEndPoint endPoint)
  281. {
  282. /* Catch EACCES and turn on SO_BROADCAST then,
  283. * as UDP sockets don't have it set by default
  284. */
  285. try {
  286. if (endPoint == null) {
  287. return(socket.Send (dgram, 0, bytes,
  288. SocketFlags.None));
  289. } else {
  290. return(socket.SendTo (dgram, 0, bytes,
  291. SocketFlags.None,
  292. endPoint));
  293. }
  294. } catch (SocketException ex) {
  295. if (ex.ErrorCode == (int)SocketError.AccessDenied) {
  296. socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  297. if (endPoint == null) {
  298. return(socket.Send (dgram, 0, bytes, SocketFlags.None));
  299. } else {
  300. return(socket.SendTo (dgram, 0, bytes, SocketFlags.None, endPoint));
  301. }
  302. } else {
  303. throw;
  304. }
  305. }
  306. }
  307. public int Send (byte [] dgram, int bytes)
  308. {
  309. CheckDisposed ();
  310. if (dgram == null)
  311. throw new ArgumentNullException ("dgram");
  312. if (!active)
  313. throw new InvalidOperationException ("Operation not allowed on " +
  314. "non-connected sockets.");
  315. return(DoSend (dgram, bytes, null));
  316. }
  317. public int Send (byte [] dgram, int bytes, IPEndPoint endPoint)
  318. {
  319. CheckDisposed ();
  320. if (dgram == null)
  321. throw new ArgumentNullException ("dgram is null");
  322. if (active) {
  323. if (endPoint != null)
  324. throw new InvalidOperationException ("Cannot send packets to an " +
  325. "arbitrary host while connected.");
  326. return(DoSend (dgram, bytes, null));
  327. }
  328. return(DoSend (dgram, bytes, endPoint));
  329. }
  330. public int Send (byte [] dgram, int bytes, string hostname, int port)
  331. {
  332. return Send (dgram, bytes,
  333. new IPEndPoint (Dns.Resolve (hostname).AddressList [0], port));
  334. }
  335. private byte [] CutArray (byte [] orig, int length)
  336. {
  337. byte [] newArray = new byte [length];
  338. Buffer.BlockCopy (orig, 0, newArray, 0, length);
  339. return newArray;
  340. }
  341. #endregion
  342. #if NET_2_0
  343. IAsyncResult DoBeginSend (byte[] datagram, int bytes,
  344. IPEndPoint endPoint,
  345. AsyncCallback requestCallback,
  346. object state)
  347. {
  348. /* Catch EACCES and turn on SO_BROADCAST then,
  349. * as UDP sockets don't have it set by default
  350. */
  351. try {
  352. if (endPoint == null) {
  353. return(socket.BeginSend (datagram, 0, bytes, SocketFlags.None, requestCallback, state));
  354. } else {
  355. return(socket.BeginSendTo (datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state));
  356. }
  357. } catch (SocketException ex) {
  358. if (ex.ErrorCode == (int)SocketError.AccessDenied) {
  359. socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  360. if (endPoint == null) {
  361. return(socket.BeginSend (datagram, 0, bytes, SocketFlags.None, requestCallback, state));
  362. } else {
  363. return(socket.BeginSendTo (datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state));
  364. }
  365. } else {
  366. throw;
  367. }
  368. }
  369. }
  370. public IAsyncResult BeginSend (byte[] datagram, int bytes,
  371. AsyncCallback requestCallback,
  372. object state)
  373. {
  374. return(BeginSend (datagram, bytes, null,
  375. requestCallback, state));
  376. }
  377. public IAsyncResult BeginSend (byte[] datagram, int bytes,
  378. IPEndPoint endPoint,
  379. AsyncCallback requestCallback,
  380. object state)
  381. {
  382. CheckDisposed ();
  383. if (datagram == null) {
  384. throw new ArgumentNullException ("datagram");
  385. }
  386. return(DoBeginSend (datagram, bytes, endPoint,
  387. requestCallback, state));
  388. }
  389. public IAsyncResult BeginSend (byte[] datagram, int bytes,
  390. string hostname, int port,
  391. AsyncCallback requestCallback,
  392. object state)
  393. {
  394. return(BeginSend (datagram, bytes, new IPEndPoint (Dns.Resolve (hostname).AddressList[0], port), requestCallback, state));
  395. }
  396. public int EndSend (IAsyncResult asyncResult)
  397. {
  398. CheckDisposed ();
  399. if (asyncResult == null) {
  400. throw new ArgumentNullException ("asyncResult is a null reference");
  401. }
  402. return(socket.EndSend (asyncResult));
  403. }
  404. public IAsyncResult BeginReceive (AsyncCallback callback,
  405. object state)
  406. {
  407. CheckDisposed ();
  408. recvbuffer = new byte[8192];
  409. EndPoint ep;
  410. if (family == AddressFamily.InterNetwork) {
  411. ep = new IPEndPoint (IPAddress.Any, 0);
  412. } else {
  413. ep = new IPEndPoint (IPAddress.IPv6Any, 0);
  414. }
  415. return(socket.BeginReceiveFrom (recvbuffer, 0, 8192,
  416. SocketFlags.None,
  417. ref ep,
  418. callback, state));
  419. }
  420. public byte[] EndReceive (IAsyncResult asyncResult,
  421. ref IPEndPoint remoteEP)
  422. {
  423. CheckDisposed ();
  424. if (asyncResult == null) {
  425. throw new ArgumentNullException ("asyncResult is a null reference");
  426. }
  427. EndPoint ep;
  428. if (family == AddressFamily.InterNetwork) {
  429. ep = new IPEndPoint (IPAddress.Any, 0);
  430. } else {
  431. ep = new IPEndPoint (IPAddress.IPv6Any, 0);
  432. }
  433. int bytes = socket.EndReceiveFrom (asyncResult,
  434. ref ep);
  435. remoteEP = (IPEndPoint)ep;
  436. /* Need to copy into a new array here, because
  437. * otherwise the returned array length is not
  438. * 'bytes'
  439. */
  440. byte[] buf = new byte[bytes];
  441. Array.Copy (recvbuffer, buf, bytes);
  442. return(buf);
  443. }
  444. #endif
  445. #region Properties
  446. protected bool Active {
  447. get { return active; }
  448. set { active = value; }
  449. }
  450. #if NET_2_0
  451. public
  452. #else
  453. protected
  454. #endif
  455. Socket Client {
  456. get { return socket; }
  457. set { socket = value; }
  458. }
  459. #if NET_2_0
  460. public int Available
  461. {
  462. get {
  463. return(socket.Available);
  464. }
  465. }
  466. public bool DontFragment
  467. {
  468. get {
  469. return(socket.DontFragment);
  470. }
  471. set {
  472. socket.DontFragment = value;
  473. }
  474. }
  475. public bool EnableBroadcast
  476. {
  477. get {
  478. return(socket.EnableBroadcast);
  479. }
  480. set {
  481. socket.EnableBroadcast = value;
  482. }
  483. }
  484. public bool ExclusiveAddressUse
  485. {
  486. get {
  487. return(socket.ExclusiveAddressUse);
  488. }
  489. set {
  490. socket.ExclusiveAddressUse = value;
  491. }
  492. }
  493. public bool MulticastLoopback
  494. {
  495. get {
  496. return(socket.MulticastLoopback);
  497. }
  498. set {
  499. socket.MulticastLoopback = value;
  500. }
  501. }
  502. public short Ttl
  503. {
  504. get {
  505. return(socket.Ttl);
  506. }
  507. set {
  508. socket.Ttl = value;
  509. }
  510. }
  511. #endif
  512. #endregion
  513. #region Disposing
  514. void IDisposable.Dispose ()
  515. {
  516. Dispose (true);
  517. GC.SuppressFinalize (this);
  518. }
  519. #if NET_2_0
  520. protected virtual
  521. #endif
  522. void Dispose (bool disposing)
  523. {
  524. if (disposed)
  525. return;
  526. disposed = true;
  527. if (disposing){
  528. if (socket != null)
  529. socket.Close ();
  530. socket = null;
  531. }
  532. }
  533. ~UdpClient ()
  534. {
  535. Dispose (false);
  536. }
  537. private void CheckDisposed ()
  538. {
  539. if (disposed)
  540. throw new ObjectDisposedException (GetType().FullName);
  541. }
  542. #endregion
  543. #endregion
  544. }
  545. }