UdpClient.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  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.InterNetworkV6)
  47. throw new ArgumentException("Family must be InterNetwork or InterNetworkV6", "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. socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
  100. if (localEP != null)
  101. socket.Bind (localEP);
  102. }
  103. #endregion // Constructors
  104. #region Public methods
  105. #region Close
  106. public void Close ()
  107. {
  108. ((IDisposable) this).Dispose ();
  109. }
  110. #endregion
  111. #region Connect
  112. public void Connect (IPEndPoint endPoint)
  113. {
  114. CheckDisposed ();
  115. if (endPoint == null)
  116. throw new ArgumentNullException ("endPoint");
  117. socket.Connect (endPoint);
  118. active = true;
  119. }
  120. public void Connect (IPAddress addr, int port)
  121. {
  122. if (addr == null)
  123. throw new ArgumentNullException ("addr");
  124. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  125. throw new ArgumentOutOfRangeException ("port");
  126. Connect (new IPEndPoint (addr, port));
  127. }
  128. public void Connect (string hostname, int port)
  129. {
  130. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  131. throw new ArgumentOutOfRangeException ("port");
  132. IPAddress[] addresses = Dns.Resolve (hostname).AddressList;
  133. for(int i=0; i<addresses.Length; i++) {
  134. try {
  135. this.family = addresses[i].AddressFamily;
  136. Connect (new IPEndPoint (addresses[i], port));
  137. break;
  138. } catch(Exception e) {
  139. if(i == addresses.Length - 1){
  140. if(socket != null) {
  141. socket.Close();
  142. socket = null;
  143. }
  144. /// This is the last entry, re-throw the exception
  145. throw e;
  146. }
  147. }
  148. }
  149. }
  150. #endregion
  151. #region Multicast methods
  152. public void DropMulticastGroup (IPAddress multicastAddr)
  153. {
  154. CheckDisposed ();
  155. if (multicastAddr == null)
  156. throw new ArgumentNullException ("multicastAddr");
  157. if(family == AddressFamily.InterNetwork)
  158. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
  159. new MulticastOption (multicastAddr));
  160. #if NET_1_1
  161. else
  162. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
  163. new IPv6MulticastOption (multicastAddr));
  164. #endif
  165. }
  166. #if NET_1_1
  167. public void DropMulticastGroup (IPAddress multicastAddr,
  168. int ifindex)
  169. {
  170. CheckDisposed ();
  171. /* LAMESPEC: exceptions haven't been specified
  172. * for this overload.
  173. */
  174. if (multicastAddr == null) {
  175. throw new ArgumentNullException ("multicastAddr");
  176. }
  177. /* Does this overload only apply to IPv6?
  178. * Only the IPv6MulticastOption has an
  179. * ifindex-using constructor. The MS docs
  180. * don't say.
  181. */
  182. if (family == AddressFamily.InterNetworkV6) {
  183. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new IPv6MulticastOption (multicastAddr, ifindex));
  184. }
  185. }
  186. #endif
  187. public void JoinMulticastGroup (IPAddress multicastAddr)
  188. {
  189. CheckDisposed ();
  190. if(family == AddressFamily.InterNetwork)
  191. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
  192. new MulticastOption (multicastAddr));
  193. #if NET_1_1
  194. else
  195. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
  196. new IPv6MulticastOption (multicastAddr));
  197. #endif
  198. }
  199. #if NET_1_1
  200. public void JoinMulticastGroup (int ifindex,
  201. IPAddress multicastAddr)
  202. {
  203. CheckDisposed ();
  204. /* Does this overload only apply to IPv6?
  205. * Only the IPv6MulticastOption has an
  206. * ifindex-using constructor. The MS docs
  207. * don't say.
  208. */
  209. if (family == AddressFamily.InterNetworkV6) {
  210. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption (multicastAddr, ifindex));
  211. }
  212. }
  213. #endif
  214. public void JoinMulticastGroup (IPAddress multicastAddr, int timeToLive)
  215. {
  216. CheckDisposed ();
  217. JoinMulticastGroup (multicastAddr);
  218. if (timeToLive < 0 || timeToLive > 255)
  219. throw new ArgumentOutOfRangeException ("timeToLive");
  220. if(family == AddressFamily.InterNetwork)
  221. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive,
  222. timeToLive);
  223. #if NET_1_1
  224. else
  225. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive,
  226. timeToLive);
  227. #endif
  228. }
  229. #endregion
  230. #region Data I/O
  231. public byte [] Receive (ref IPEndPoint remoteEP)
  232. {
  233. CheckDisposed ();
  234. // Bug 45633: the spec states that we should block until a datagram arrives:
  235. // remove the 512 hardcoded value.
  236. // Block until we get it.
  237. socket.Poll (-1, SelectMode.SelectRead);
  238. byte [] recBuffer;
  239. int available = socket.Available;
  240. recBuffer = new byte [available];
  241. EndPoint endPoint = new IPEndPoint (IPAddress.Any, 0);
  242. int dataRead = socket.ReceiveFrom (recBuffer, ref endPoint);
  243. if (dataRead < recBuffer.Length)
  244. recBuffer = CutArray (recBuffer, dataRead);
  245. remoteEP = (IPEndPoint) endPoint;
  246. return recBuffer;
  247. }
  248. public int Send (byte [] dgram, int bytes)
  249. {
  250. CheckDisposed ();
  251. if (dgram == null)
  252. throw new ArgumentNullException ("dgram");
  253. if (!active)
  254. throw new InvalidOperationException ("Operation not allowed on " +
  255. "non-connected sockets.");
  256. return socket.Send (dgram, 0, bytes, SocketFlags.None);
  257. }
  258. public int Send (byte [] dgram, int bytes, IPEndPoint endPoint)
  259. {
  260. CheckDisposed ();
  261. if (dgram == null)
  262. throw new ArgumentNullException ("dgram is null");
  263. if (active) {
  264. if (endPoint != null)
  265. throw new InvalidOperationException ("Cannot send packets to an " +
  266. "arbitrary host while connected.");
  267. return socket.Send (dgram, 0, bytes, SocketFlags.None);
  268. }
  269. return socket.SendTo (dgram, 0, bytes, SocketFlags.None, endPoint);
  270. }
  271. public int Send (byte [] dgram, int bytes, string hostname, int port)
  272. {
  273. return Send (dgram, bytes,
  274. new IPEndPoint (Dns.Resolve (hostname).AddressList [0], port));
  275. }
  276. private byte [] CutArray (byte [] orig, int length)
  277. {
  278. byte [] newArray = new byte [length];
  279. Buffer.BlockCopy (orig, 0, newArray, 0, length);
  280. return newArray;
  281. }
  282. #endregion
  283. #region Properties
  284. protected bool Active {
  285. get { return active; }
  286. set { active = value; }
  287. }
  288. protected Socket Client {
  289. get { return socket; }
  290. set { socket = value; }
  291. }
  292. #endregion
  293. #region Disposing
  294. void IDisposable.Dispose ()
  295. {
  296. Dispose (true);
  297. GC.SuppressFinalize (this);
  298. }
  299. void Dispose (bool disposing)
  300. {
  301. if (disposed)
  302. return;
  303. disposed = true;
  304. if (disposing){
  305. if (socket != null)
  306. socket.Close ();
  307. socket = null;
  308. }
  309. }
  310. ~UdpClient ()
  311. {
  312. Dispose (false);
  313. }
  314. private void CheckDisposed ()
  315. {
  316. if (disposed)
  317. throw new ObjectDisposedException (GetType().FullName);
  318. }
  319. #endregion
  320. #endregion
  321. }
  322. }