UdpClient.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. public void Close ()
  105. {
  106. Dispose ();
  107. }
  108. #region Connect
  109. void DoConnect (IPEndPoint endPoint)
  110. {
  111. /* Catch EACCES and turn on SO_BROADCAST then,
  112. * as UDP sockets don't have it set by default
  113. */
  114. try {
  115. socket.Connect (endPoint);
  116. } catch (SocketException ex) {
  117. if (ex.ErrorCode == (int)SocketError.AccessDenied) {
  118. socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  119. socket.Connect (endPoint);
  120. } else {
  121. throw;
  122. }
  123. }
  124. }
  125. public void Connect (IPEndPoint endPoint)
  126. {
  127. CheckDisposed ();
  128. if (endPoint == null)
  129. throw new ArgumentNullException ("endPoint");
  130. DoConnect (endPoint);
  131. active = true;
  132. }
  133. public void Connect (IPAddress addr, int port)
  134. {
  135. if (addr == null)
  136. throw new ArgumentNullException ("addr");
  137. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  138. throw new ArgumentOutOfRangeException ("port");
  139. Connect (new IPEndPoint (addr, port));
  140. }
  141. public void Connect (string hostname, int port)
  142. {
  143. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  144. throw new ArgumentOutOfRangeException ("port");
  145. IPAddress[] addresses = Dns.GetHostAddresses (hostname);
  146. for(int i=0; i<addresses.Length; i++) {
  147. try {
  148. this.family = addresses[i].AddressFamily;
  149. Connect (new IPEndPoint (addresses[i], port));
  150. break;
  151. } catch(Exception e) {
  152. if(i == addresses.Length - 1){
  153. if(socket != null) {
  154. socket.Close();
  155. socket = null;
  156. }
  157. /// This is the last entry, re-throw the exception
  158. throw e;
  159. }
  160. }
  161. }
  162. }
  163. #endregion
  164. #region Multicast methods
  165. public void DropMulticastGroup (IPAddress multicastAddr)
  166. {
  167. CheckDisposed ();
  168. if (multicastAddr == null)
  169. throw new ArgumentNullException ("multicastAddr");
  170. if(family == AddressFamily.InterNetwork)
  171. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
  172. new MulticastOption (multicastAddr));
  173. else
  174. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
  175. new IPv6MulticastOption (multicastAddr));
  176. }
  177. public void DropMulticastGroup (IPAddress multicastAddr,
  178. int ifindex)
  179. {
  180. CheckDisposed ();
  181. /* LAMESPEC: exceptions haven't been specified
  182. * for this overload.
  183. */
  184. if (multicastAddr == null) {
  185. throw new ArgumentNullException ("multicastAddr");
  186. }
  187. /* Does this overload only apply to IPv6?
  188. * Only the IPv6MulticastOption has an
  189. * ifindex-using constructor. The MS docs
  190. * don't say.
  191. */
  192. if (family == AddressFamily.InterNetworkV6) {
  193. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new IPv6MulticastOption (multicastAddr, ifindex));
  194. }
  195. }
  196. public void JoinMulticastGroup (IPAddress multicastAddr)
  197. {
  198. CheckDisposed ();
  199. if (multicastAddr == null)
  200. throw new ArgumentNullException ("multicastAddr");
  201. if(family == AddressFamily.InterNetwork)
  202. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
  203. new MulticastOption (multicastAddr));
  204. else
  205. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
  206. new IPv6MulticastOption (multicastAddr));
  207. }
  208. public void JoinMulticastGroup (int ifindex,
  209. IPAddress multicastAddr)
  210. {
  211. CheckDisposed ();
  212. if (multicastAddr == null)
  213. throw new ArgumentNullException ("multicastAddr");
  214. if (family == AddressFamily.InterNetworkV6)
  215. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption (multicastAddr, ifindex));
  216. else
  217. throw new SocketException ((int) SocketError.OperationNotSupported);
  218. }
  219. public void JoinMulticastGroup (IPAddress multicastAddr, int timeToLive)
  220. {
  221. CheckDisposed ();
  222. if (multicastAddr == null)
  223. throw new ArgumentNullException ("multicastAddr");
  224. if (timeToLive < 0 || timeToLive > 255)
  225. throw new ArgumentOutOfRangeException ("timeToLive");
  226. JoinMulticastGroup (multicastAddr);
  227. if(family == AddressFamily.InterNetwork)
  228. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive,
  229. timeToLive);
  230. else
  231. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive,
  232. timeToLive);
  233. }
  234. public void JoinMulticastGroup (IPAddress multicastAddr,
  235. IPAddress localAddress)
  236. {
  237. CheckDisposed ();
  238. if (family == AddressFamily.InterNetwork)
  239. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption (multicastAddr, localAddress));
  240. else
  241. throw new SocketException ((int) SocketError.OperationNotSupported);
  242. }
  243. #endregion
  244. #region Data I/O
  245. public byte [] Receive (ref IPEndPoint remoteEP)
  246. {
  247. CheckDisposed ();
  248. byte [] recBuffer = new byte [65536]; // Max. size
  249. EndPoint endPoint = (EndPoint) remoteEP;
  250. int dataRead = socket.ReceiveFrom (recBuffer, ref endPoint);
  251. if (dataRead < recBuffer.Length)
  252. recBuffer = CutArray (recBuffer, dataRead);
  253. remoteEP = (IPEndPoint) endPoint;
  254. return recBuffer;
  255. }
  256. int DoSend (byte[] dgram, int bytes, IPEndPoint endPoint)
  257. {
  258. /* Catch EACCES and turn on SO_BROADCAST then,
  259. * as UDP sockets don't have it set by default
  260. */
  261. try {
  262. if (endPoint == null) {
  263. return(socket.Send (dgram, 0, bytes,
  264. SocketFlags.None));
  265. } else {
  266. return(socket.SendTo (dgram, 0, bytes,
  267. SocketFlags.None,
  268. endPoint));
  269. }
  270. } catch (SocketException ex) {
  271. if (ex.ErrorCode == (int)SocketError.AccessDenied) {
  272. socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  273. if (endPoint == null) {
  274. return(socket.Send (dgram, 0, bytes, SocketFlags.None));
  275. } else {
  276. return(socket.SendTo (dgram, 0, bytes, SocketFlags.None, endPoint));
  277. }
  278. } else {
  279. throw;
  280. }
  281. }
  282. }
  283. public int Send (byte [] dgram, int bytes)
  284. {
  285. CheckDisposed ();
  286. if (dgram == null)
  287. throw new ArgumentNullException ("dgram");
  288. if (!active)
  289. throw new InvalidOperationException ("Operation not allowed on " +
  290. "non-connected sockets.");
  291. return(DoSend (dgram, bytes, null));
  292. }
  293. public int Send (byte [] dgram, int bytes, IPEndPoint endPoint)
  294. {
  295. CheckDisposed ();
  296. if (dgram == null)
  297. throw new ArgumentNullException ("dgram is null");
  298. if (active) {
  299. if (endPoint != null)
  300. throw new InvalidOperationException ("Cannot send packets to an " +
  301. "arbitrary host while connected.");
  302. return(DoSend (dgram, bytes, null));
  303. }
  304. return(DoSend (dgram, bytes, endPoint));
  305. }
  306. public int Send (byte [] dgram, int bytes, string hostname, int port)
  307. {
  308. return Send (dgram, bytes,
  309. new IPEndPoint (Dns.GetHostAddresses (hostname) [0], port));
  310. }
  311. private byte [] CutArray (byte [] orig, int length)
  312. {
  313. byte [] newArray = new byte [length];
  314. Buffer.BlockCopy (orig, 0, newArray, 0, length);
  315. return newArray;
  316. }
  317. #endregion
  318. IAsyncResult DoBeginSend (byte[] datagram, int bytes,
  319. IPEndPoint endPoint,
  320. AsyncCallback requestCallback,
  321. object state)
  322. {
  323. /* Catch EACCES and turn on SO_BROADCAST then,
  324. * as UDP sockets don't have it set by default
  325. */
  326. try {
  327. if (endPoint == null) {
  328. return(socket.BeginSend (datagram, 0, bytes, SocketFlags.None, requestCallback, state));
  329. } else {
  330. return(socket.BeginSendTo (datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state));
  331. }
  332. } catch (SocketException ex) {
  333. if (ex.ErrorCode == (int)SocketError.AccessDenied) {
  334. socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  335. if (endPoint == null) {
  336. return(socket.BeginSend (datagram, 0, bytes, SocketFlags.None, requestCallback, state));
  337. } else {
  338. return(socket.BeginSendTo (datagram, 0, bytes, SocketFlags.None, endPoint, requestCallback, state));
  339. }
  340. } else {
  341. throw;
  342. }
  343. }
  344. }
  345. public IAsyncResult BeginSend (byte[] datagram, int bytes,
  346. AsyncCallback requestCallback,
  347. object state)
  348. {
  349. return(BeginSend (datagram, bytes, null,
  350. requestCallback, state));
  351. }
  352. public IAsyncResult BeginSend (byte[] datagram, int bytes,
  353. IPEndPoint endPoint,
  354. AsyncCallback requestCallback,
  355. object state)
  356. {
  357. CheckDisposed ();
  358. if (datagram == null) {
  359. throw new ArgumentNullException ("datagram");
  360. }
  361. return(DoBeginSend (datagram, bytes, endPoint,
  362. requestCallback, state));
  363. }
  364. public IAsyncResult BeginSend (byte[] datagram, int bytes,
  365. string hostname, int port,
  366. AsyncCallback requestCallback,
  367. object state)
  368. {
  369. return(BeginSend (datagram, bytes, new IPEndPoint (Dns.GetHostAddresses (hostname) [0], port), requestCallback, state));
  370. }
  371. public int EndSend (IAsyncResult asyncResult)
  372. {
  373. CheckDisposed ();
  374. if (asyncResult == null) {
  375. throw new ArgumentNullException ("asyncResult is a null reference");
  376. }
  377. return(socket.EndSend (asyncResult));
  378. }
  379. public IAsyncResult BeginReceive (AsyncCallback requestCallback, object state)
  380. {
  381. CheckDisposed ();
  382. recvbuffer = new byte[8192];
  383. EndPoint ep;
  384. if (family == AddressFamily.InterNetwork) {
  385. ep = new IPEndPoint (IPAddress.Any, 0);
  386. } else {
  387. ep = new IPEndPoint (IPAddress.IPv6Any, 0);
  388. }
  389. return(socket.BeginReceiveFrom (recvbuffer, 0, 8192,
  390. SocketFlags.None,
  391. ref ep,
  392. requestCallback, state));
  393. }
  394. public byte[] EndReceive (IAsyncResult asyncResult, ref IPEndPoint remoteEP)
  395. {
  396. CheckDisposed ();
  397. if (asyncResult == null) {
  398. throw new ArgumentNullException ("asyncResult is a null reference");
  399. }
  400. EndPoint ep;
  401. if (family == AddressFamily.InterNetwork) {
  402. ep = new IPEndPoint (IPAddress.Any, 0);
  403. } else {
  404. ep = new IPEndPoint (IPAddress.IPv6Any, 0);
  405. }
  406. int bytes = socket.EndReceiveFrom (asyncResult,
  407. ref ep);
  408. remoteEP = (IPEndPoint)ep;
  409. /* Need to copy into a new array here, because
  410. * otherwise the returned array length is not
  411. * 'bytes'
  412. */
  413. byte[] buf = new byte[bytes];
  414. Array.Copy (recvbuffer, buf, bytes);
  415. return(buf);
  416. }
  417. #region Properties
  418. protected bool Active {
  419. get { return active; }
  420. set { active = value; }
  421. }
  422. public Socket Client {
  423. get { return socket; }
  424. set { socket = value; }
  425. }
  426. public int Available
  427. {
  428. get {
  429. return(socket.Available);
  430. }
  431. }
  432. public bool DontFragment
  433. {
  434. get {
  435. return(socket.DontFragment);
  436. }
  437. set {
  438. socket.DontFragment = value;
  439. }
  440. }
  441. public bool EnableBroadcast
  442. {
  443. get {
  444. return(socket.EnableBroadcast);
  445. }
  446. set {
  447. socket.EnableBroadcast = value;
  448. }
  449. }
  450. public bool ExclusiveAddressUse
  451. {
  452. get {
  453. return(socket.ExclusiveAddressUse);
  454. }
  455. set {
  456. socket.ExclusiveAddressUse = value;
  457. }
  458. }
  459. public bool MulticastLoopback
  460. {
  461. get {
  462. return(socket.MulticastLoopback);
  463. }
  464. set {
  465. socket.MulticastLoopback = value;
  466. }
  467. }
  468. public short Ttl
  469. {
  470. get {
  471. return(socket.Ttl);
  472. }
  473. set {
  474. socket.Ttl = value;
  475. }
  476. }
  477. #endregion
  478. #region Disposing
  479. public void Dispose ()
  480. {
  481. Dispose (true);
  482. GC.SuppressFinalize (this);
  483. }
  484. protected virtual void Dispose (bool disposing)
  485. {
  486. if (disposed)
  487. return;
  488. disposed = true;
  489. if (disposing){
  490. if (socket != null)
  491. socket.Close ();
  492. socket = null;
  493. }
  494. }
  495. ~UdpClient ()
  496. {
  497. Dispose (false);
  498. }
  499. private void CheckDisposed ()
  500. {
  501. if (disposed)
  502. throw new ObjectDisposedException (GetType().FullName);
  503. }
  504. #endregion
  505. public Task<UdpReceiveResult> ReceiveAsync ()
  506. {
  507. return Task<UdpReceiveResult>.Factory.FromAsync (BeginReceive, r => {
  508. IPEndPoint remoteEndPoint = null;
  509. return new UdpReceiveResult (EndReceive (r, ref remoteEndPoint), remoteEndPoint);
  510. }, null);
  511. }
  512. public Task<int> SendAsync (byte[] datagram, int bytes)
  513. {
  514. return Task<int>.Factory.FromAsync (BeginSend, EndSend, datagram, bytes, null);
  515. }
  516. public Task<int> SendAsync (byte[] datagram, int bytes, IPEndPoint endPoint)
  517. {
  518. return Task<int>.Factory.FromAsync (BeginSend, EndSend, datagram, bytes, endPoint, null);
  519. }
  520. public Task<int> SendAsync (byte[] datagram, int bytes, string hostname, int port)
  521. {
  522. var t = Tuple.Create (datagram, bytes, hostname, port, this);
  523. return Task<int>.Factory.FromAsync ((callback, state) => {
  524. var d = (Tuple<byte[], int, string, int, UdpClient>) state;
  525. return d.Item5.BeginSend (d.Item1, d.Item2, d.Item3, d.Item4, callback, null);
  526. }, EndSend, t);
  527. }
  528. }
  529. }