UdpClient.cs 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. using System;
  10. using System.Net;
  11. namespace System.Net.Sockets
  12. {
  13. public class UdpClient : IDisposable
  14. {
  15. private bool disposed = false;
  16. private bool active = false;
  17. private Socket socket;
  18. private AddressFamily family = AddressFamily.InterNetwork;
  19. #region Constructors
  20. public UdpClient () : this(AddressFamily.InterNetwork)
  21. {
  22. }
  23. public UdpClient(AddressFamily family)
  24. {
  25. if(family != AddressFamily.InterNetwork && family != AddressFamily.InterNetwork)
  26. throw new ArgumentException("family");
  27. this.family = family;
  28. InitSocket (null);
  29. }
  30. public UdpClient (int port)
  31. {
  32. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  33. throw new ArgumentOutOfRangeException ("port");
  34. this.family = AddressFamily.InterNetwork;
  35. IPEndPoint localEP = new IPEndPoint (IPAddress.Any, port);
  36. InitSocket (localEP);
  37. }
  38. public UdpClient (IPEndPoint localEP)
  39. {
  40. if (localEP == null)
  41. throw new ArgumentNullException ("localEP");
  42. this.family = localEP.AddressFamily;
  43. InitSocket (localEP);
  44. }
  45. public UdpClient (string hostname, int port)
  46. {
  47. if (hostname == null)
  48. throw new ArgumentNullException ("hostname");
  49. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  50. throw new ArgumentOutOfRangeException ("port");
  51. InitSocket (null);
  52. Connect (hostname, port);
  53. }
  54. private void InitSocket (EndPoint localEP)
  55. {
  56. if(socket != null) {
  57. socket.Close();
  58. socket = null;
  59. }
  60. socket = new Socket (family, SocketType.Dgram, ProtocolType.Udp);
  61. if (localEP != null)
  62. socket.Bind (localEP);
  63. }
  64. #endregion // Constructors
  65. #region Public methods
  66. #region Close
  67. public void Close ()
  68. {
  69. ((IDisposable) this).Dispose ();
  70. }
  71. #endregion
  72. #region Connect
  73. public void Connect (IPEndPoint endPoint)
  74. {
  75. CheckDisposed ();
  76. if (endPoint == null)
  77. throw new ArgumentNullException ("endPoint");
  78. socket.Connect (endPoint);
  79. active = true;
  80. }
  81. public void Connect (IPAddress addr, int port)
  82. {
  83. if (addr == null)
  84. throw new ArgumentNullException ("addr");
  85. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  86. throw new ArgumentOutOfRangeException ("port");
  87. Connect (new IPEndPoint (addr, port));
  88. }
  89. public void Connect (string hostname, int port)
  90. {
  91. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  92. throw new ArgumentOutOfRangeException ("port");
  93. IPAddress[] addresses = Dns.Resolve (hostname).AddressList;
  94. for(int i=0; i<addresses.Length; i++) {
  95. try {
  96. Console.WriteLine("Trying: {0}, Family: {1}", addresses[i], addresses[i].AddressFamily);
  97. this.family = addresses[i].AddressFamily;
  98. Connect (new IPEndPoint (addresses[i], port));
  99. Console.WriteLine("Connected: {0}, Family: {1}", addresses[i], family);
  100. break;
  101. }
  102. catch(Exception e) {
  103. if(i == addresses.Length - 1){
  104. if(socket != null) {
  105. socket.Close();
  106. socket = null;
  107. }
  108. /// This is the last entry, re-throw the exception
  109. throw e;
  110. }
  111. }
  112. }
  113. }
  114. #endregion
  115. #region Multicast methods
  116. public void DropMulticastGroup (IPAddress multicastAddr)
  117. {
  118. CheckDisposed ();
  119. if (multicastAddr == null)
  120. throw new ArgumentNullException ("multicastAddr");
  121. if(family == AddressFamily.InterNetwork)
  122. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DropMembership,
  123. new MulticastOption (multicastAddr));
  124. #if NET_1_1
  125. else
  126. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DropMembership,
  127. new IPv6MulticastOption (multicastAddr));
  128. #endif
  129. }
  130. public void JoinMulticastGroup (IPAddress multicastAddr)
  131. {
  132. CheckDisposed ();
  133. if(family == AddressFamily.InterNetwork)
  134. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.AddMembership,
  135. new MulticastOption (multicastAddr));
  136. #if NET_1_1
  137. else
  138. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.AddMembership,
  139. new IPv6MulticastOption (multicastAddr));
  140. #endif
  141. }
  142. public void JoinMulticastGroup (IPAddress multicastAddr, int timeToLive)
  143. {
  144. CheckDisposed ();
  145. JoinMulticastGroup (multicastAddr);
  146. if (timeToLive < 0 || timeToLive > 255)
  147. throw new ArgumentOutOfRangeException ("timeToLive");
  148. if(family == AddressFamily.InterNetwork)
  149. socket.SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive,
  150. timeToLive);
  151. #if NET_1_1
  152. else
  153. socket.SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive,
  154. timeToLive);
  155. #endif
  156. }
  157. #endregion
  158. #region Data I/O
  159. public byte [] Receive (ref IPEndPoint remoteEP)
  160. {
  161. CheckDisposed ();
  162. // Length of the array for receiving data??
  163. byte [] recBuffer;
  164. int available = socket.Available;
  165. if (available < 512)
  166. available = 512;
  167. recBuffer = new byte [available];
  168. EndPoint endPoint = new IPEndPoint (IPAddress.Any, 0);
  169. int dataRead = socket.ReceiveFrom (recBuffer, ref endPoint);
  170. if (dataRead < recBuffer.Length)
  171. recBuffer = CutArray (recBuffer, dataRead);
  172. remoteEP = (IPEndPoint) endPoint;
  173. return recBuffer;
  174. }
  175. public int Send (byte [] dgram, int bytes)
  176. {
  177. CheckDisposed ();
  178. if (dgram == null)
  179. throw new ArgumentNullException ("dgram");
  180. if (!active)
  181. throw new InvalidOperationException ("Operation not allowed on " +
  182. "non-connected sockets.");
  183. return socket.Send (dgram, 0, bytes, SocketFlags.None);
  184. }
  185. public int Send (byte [] dgram, int bytes, IPEndPoint endPoint)
  186. {
  187. CheckDisposed ();
  188. if (dgram == null)
  189. throw new ArgumentNullException ("dgram is null");
  190. if (active) {
  191. if (endPoint != null)
  192. throw new InvalidOperationException ("Cannot send packets to an " +
  193. "arbitrary host while connected.");
  194. return socket.Send (dgram, 0, bytes, SocketFlags.None);
  195. }
  196. return socket.SendTo (dgram, 0, bytes, SocketFlags.None, endPoint);
  197. }
  198. public int Send (byte [] dgram, int bytes, string hostname, int port)
  199. {
  200. return Send (dgram, bytes,
  201. new IPEndPoint (Dns.Resolve (hostname).AddressList [0], port));
  202. }
  203. private byte [] CutArray (byte [] orig, int length)
  204. {
  205. byte [] newArray = new byte [length];
  206. Buffer.BlockCopy (orig, 0, newArray, 0, length);
  207. return newArray;
  208. }
  209. #endregion
  210. #region Properties
  211. protected bool Active {
  212. get { return active; }
  213. set { active = value; }
  214. }
  215. protected Socket Client {
  216. get { return socket; }
  217. set { socket = value; }
  218. }
  219. #endregion
  220. #region Disposing
  221. void IDisposable.Dispose ()
  222. {
  223. Dispose (true);
  224. GC.SuppressFinalize (this);
  225. }
  226. void Dispose (bool disposing)
  227. {
  228. if (disposed)
  229. return;
  230. disposed = true;
  231. if (disposing) {
  232. // release managed resources
  233. }
  234. // release unmanaged resources
  235. Socket s = socket;
  236. socket = null;
  237. if (s != null)
  238. s.Close ();
  239. }
  240. ~UdpClient ()
  241. {
  242. Dispose (false);
  243. }
  244. private void CheckDisposed ()
  245. {
  246. if (disposed)
  247. throw new ObjectDisposedException (GetType().FullName);
  248. }
  249. #endregion
  250. #endregion
  251. }
  252. }