UdpClient.cs 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. //
  2. // System.Net.Sockets.UdpClient.cs
  3. //
  4. // Author:
  5. // Gonzalo Paniagua Javier <[email protected]>
  6. //
  7. // Copyright (C) Ximian, Inc. http://www.ximian.com
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Net;
  31. namespace System.Net.Sockets
  32. {
  33. public class UdpClient : IDisposable
  34. {
  35. private bool disposed = false;
  36. private bool active = false;
  37. private Socket socket;
  38. private AddressFamily family = AddressFamily.InterNetwork;
  39. #region Constructors
  40. public UdpClient () : this(AddressFamily.InterNetwork)
  41. {
  42. }
  43. #if NET_1_1
  44. public UdpClient(AddressFamily family)
  45. {
  46. if(family != AddressFamily.InterNetwork && family != AddressFamily.InterNetwork)
  47. throw new ArgumentException("family");
  48. this.family = family;
  49. InitSocket (null);
  50. }
  51. #endif
  52. public UdpClient (int port)
  53. {
  54. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  55. throw new ArgumentOutOfRangeException ("port");
  56. this.family = AddressFamily.InterNetwork;
  57. IPEndPoint localEP = new IPEndPoint (IPAddress.Any, port);
  58. InitSocket (localEP);
  59. }
  60. public UdpClient (IPEndPoint localEP)
  61. {
  62. if (localEP == null)
  63. throw new ArgumentNullException ("localEP");
  64. this.family = localEP.AddressFamily;
  65. InitSocket (localEP);
  66. }
  67. #if NET_1_1
  68. public UdpClient (int port, AddressFamily family)
  69. {
  70. if (family != AddressFamily.InterNetwork &&
  71. family != AddressFamily.InterNetworkV6) {
  72. throw new ArgumentException ("Family must be InterNetwork or InterNetworkV6", "family");
  73. }
  74. if (port < IPEndPoint.MinPort ||
  75. port > IPEndPoint.MaxPort) {
  76. throw new ArgumentOutOfRangeException ("port");
  77. }
  78. this.family = family;
  79. IPEndPoint localEP = new IPEndPoint (IPAddress.Any, port);
  80. InitSocket (localEP);
  81. }
  82. #endif
  83. public UdpClient (string hostname, int port)
  84. {
  85. if (hostname == null)
  86. throw new ArgumentNullException ("hostname");
  87. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  88. throw new ArgumentOutOfRangeException ("port");
  89. InitSocket (null);
  90. Connect (hostname, port);
  91. }
  92. private void InitSocket (EndPoint localEP)
  93. {
  94. if(socket != null) {
  95. socket.Close();
  96. socket = null;
  97. }
  98. socket = new Socket (family, SocketType.Dgram, ProtocolType.Udp);
  99. if (localEP != null)
  100. socket.Bind (localEP);
  101. }
  102. #endregion // Constructors
  103. #region Public methods
  104. #region Close
  105. public void Close ()
  106. {
  107. ((IDisposable) this).Dispose ();
  108. }
  109. #endregion
  110. #region Connect
  111. public void Connect (IPEndPoint endPoint)
  112. {
  113. CheckDisposed ();
  114. if (endPoint == null)
  115. throw new ArgumentNullException ("endPoint");
  116. socket.Connect (endPoint);
  117. active = true;
  118. }
  119. public void Connect (IPAddress addr, int port)
  120. {
  121. if (addr == null)
  122. throw new ArgumentNullException ("addr");
  123. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  124. throw new ArgumentOutOfRangeException ("port");
  125. Connect (new IPEndPoint (addr, port));
  126. }
  127. public void Connect (string hostname, int port)
  128. {
  129. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  130. throw new ArgumentOutOfRangeException ("port");
  131. IPAddress[] addresses = Dns.Resolve (hostname).AddressList;
  132. for(int i=0; i<addresses.Length; i++) {
  133. try {
  134. this.family = addresses[i].AddressFamily;
  135. Connect (new IPEndPoint (addresses[i], port));
  136. break;
  137. } catch(Exception e) {
  138. if(i == addresses.Length - 1){
  139. if(socket != null) {
  140. socket.Close();
  141. socket = null;
  142. }
  143. /// This is the last entry, re-throw the exception
  144. throw e;
  145. }
  146. }
  147. }
  148. }
  149. #endregion
  150. #region Multicast methods
  151. public void DropMulticastGroup (IPAddress multicastAddr)
  152. {
  153. CheckDisposed ();
  154. if (multicastAddr == null)
  155. throw new ArgumentNullException ("multicastAddr");
  156. if(family == AddressFamily.InterNetwork)
  157. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
  158. new MulticastOption (multicastAddr));
  159. #if NET_1_1
  160. else
  161. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
  162. new IPv6MulticastOption (multicastAddr));
  163. #endif
  164. }
  165. #if NET_1_1
  166. public void DropMulticastGroup (IPAddress multicastAddr,
  167. int ifindex)
  168. {
  169. CheckDisposed ();
  170. /* LAMESPEC: exceptions haven't been specified
  171. * for this overload.
  172. */
  173. if (multicastAddr == null) {
  174. throw new ArgumentNullException ("multicastAddr");
  175. }
  176. /* Does this overload only apply to IPv6?
  177. * Only the IPv6MulticastOption has an
  178. * ifindex-using constructor. The MS docs
  179. * don't say.
  180. */
  181. if (family == AddressFamily.InterNetworkV6) {
  182. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new IPv6MulticastOption (multicastAddr, ifindex));
  183. }
  184. }
  185. #endif
  186. public void JoinMulticastGroup (IPAddress multicastAddr)
  187. {
  188. CheckDisposed ();
  189. if(family == AddressFamily.InterNetwork)
  190. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
  191. new MulticastOption (multicastAddr));
  192. #if NET_1_1
  193. else
  194. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
  195. new IPv6MulticastOption (multicastAddr));
  196. #endif
  197. }
  198. #if NET_1_1
  199. public void JoinMulticastGroup (int ifindex,
  200. IPAddress multicastAddr)
  201. {
  202. CheckDisposed ();
  203. /* Does this overload only apply to IPv6?
  204. * Only the IPv6MulticastOption has an
  205. * ifindex-using constructor. The MS docs
  206. * don't say.
  207. */
  208. if (family == AddressFamily.InterNetworkV6) {
  209. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption (multicastAddr, ifindex));
  210. }
  211. }
  212. #endif
  213. public void JoinMulticastGroup (IPAddress multicastAddr, int timeToLive)
  214. {
  215. CheckDisposed ();
  216. JoinMulticastGroup (multicastAddr);
  217. if (timeToLive < 0 || timeToLive > 255)
  218. throw new ArgumentOutOfRangeException ("timeToLive");
  219. if(family == AddressFamily.InterNetwork)
  220. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive,
  221. timeToLive);
  222. #if NET_1_1
  223. else
  224. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive,
  225. timeToLive);
  226. #endif
  227. }
  228. #endregion
  229. #region Data I/O
  230. public byte [] Receive (ref IPEndPoint remoteEP)
  231. {
  232. CheckDisposed ();
  233. // Bug 45633: the spec states that we should block until a datagram arrives:
  234. // remove the 512 hardcoded value.
  235. // Block until we get it.
  236. socket.Poll (-1, SelectMode.SelectRead);
  237. byte [] recBuffer;
  238. int available = socket.Available;
  239. recBuffer = new byte [available];
  240. EndPoint endPoint = new IPEndPoint (IPAddress.Any, 0);
  241. int dataRead = socket.ReceiveFrom (recBuffer, ref endPoint);
  242. if (dataRead < recBuffer.Length)
  243. recBuffer = CutArray (recBuffer, dataRead);
  244. remoteEP = (IPEndPoint) endPoint;
  245. return recBuffer;
  246. }
  247. public int Send (byte [] dgram, int bytes)
  248. {
  249. CheckDisposed ();
  250. if (dgram == null)
  251. throw new ArgumentNullException ("dgram");
  252. if (!active)
  253. throw new InvalidOperationException ("Operation not allowed on " +
  254. "non-connected sockets.");
  255. return socket.Send (dgram, 0, bytes, SocketFlags.None);
  256. }
  257. public int Send (byte [] dgram, int bytes, IPEndPoint endPoint)
  258. {
  259. CheckDisposed ();
  260. if (dgram == null)
  261. throw new ArgumentNullException ("dgram is null");
  262. if (active) {
  263. if (endPoint != null)
  264. throw new InvalidOperationException ("Cannot send packets to an " +
  265. "arbitrary host while connected.");
  266. return socket.Send (dgram, 0, bytes, SocketFlags.None);
  267. }
  268. return socket.SendTo (dgram, 0, bytes, SocketFlags.None, endPoint);
  269. }
  270. public int Send (byte [] dgram, int bytes, string hostname, int port)
  271. {
  272. return Send (dgram, bytes,
  273. new IPEndPoint (Dns.Resolve (hostname).AddressList [0], port));
  274. }
  275. private byte [] CutArray (byte [] orig, int length)
  276. {
  277. byte [] newArray = new byte [length];
  278. Buffer.BlockCopy (orig, 0, newArray, 0, length);
  279. return newArray;
  280. }
  281. #endregion
  282. #region Properties
  283. protected bool Active {
  284. get { return active; }
  285. set { active = value; }
  286. }
  287. protected Socket Client {
  288. get { return socket; }
  289. set { socket = value; }
  290. }
  291. #endregion
  292. #region Disposing
  293. void IDisposable.Dispose ()
  294. {
  295. Dispose (true);
  296. GC.SuppressFinalize (this);
  297. }
  298. void Dispose (bool disposing)
  299. {
  300. if (disposed)
  301. return;
  302. disposed = true;
  303. if (disposing){
  304. if (socket != null)
  305. socket.Close ();
  306. socket = null;
  307. }
  308. }
  309. ~UdpClient ()
  310. {
  311. Dispose (false);
  312. }
  313. private void CheckDisposed ()
  314. {
  315. if (disposed)
  316. throw new ObjectDisposedException (GetType().FullName);
  317. }
  318. #endregion
  319. #endregion
  320. }
  321. }