UdpClient.cs 16 KB

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