Socket.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. // System.Net.Sockets.Socket.cs
  2. //
  3. // Authors:
  4. // Phillip Pearson ([email protected])
  5. // Dick Porter <[email protected]>
  6. //
  7. // Copyright (C) 2001, 2002 Phillip Pearson and Ximian, Inc.
  8. // http://www.myelin.co.nz
  9. //
  10. using System;
  11. using System.Net;
  12. using System.Collections;
  13. using System.Runtime.CompilerServices;
  14. using System.Threading;
  15. namespace System.Net.Sockets
  16. {
  17. public class Socket : IDisposable
  18. {
  19. private sealed class SocketAsyncResult: IAsyncResult
  20. {
  21. private object state;
  22. private WaitHandle waithandle;
  23. private bool completed_sync, completed;
  24. private Worker worker;
  25. public SocketAsyncResult(object state) {
  26. this.state=state;
  27. waithandle=new ManualResetEvent(false);
  28. completed_sync=completed=false;
  29. }
  30. public object AsyncState {
  31. get {
  32. return(state);
  33. }
  34. }
  35. public WaitHandle AsyncWaitHandle {
  36. get {
  37. return(waithandle);
  38. }
  39. set {
  40. waithandle=value;
  41. }
  42. }
  43. public bool CompletedSynchronously {
  44. get {
  45. return(completed_sync);
  46. }
  47. }
  48. public bool IsCompleted {
  49. get {
  50. return(completed);
  51. }
  52. set {
  53. completed=value;
  54. }
  55. }
  56. public Worker Worker {
  57. get {
  58. return(worker);
  59. }
  60. set {
  61. worker=value;
  62. }
  63. }
  64. }
  65. private sealed class Worker
  66. {
  67. private AsyncCallback callback;
  68. private SocketAsyncResult result;
  69. private Socket socket;
  70. // Parameters
  71. private EndPoint endpoint; // Connect,ReceiveFrom,SendTo
  72. private byte[] buffer; // Receive,ReceiveFrom,Send,SendTo
  73. private int offset; // Receive,ReceiveFrom,Send,SendTo
  74. private int size; // Receive,ReceiveFrom,Send,SendTo
  75. private SocketFlags sockflags; // Receive,ReceiveFrom,Send,SendTo
  76. // Return values
  77. private Socket acc_socket;
  78. private int total;
  79. // For Accept
  80. public Worker(Socket req_sock,
  81. AsyncCallback req_callback,
  82. SocketAsyncResult req_result)
  83. : this(req_sock, null, 0, 0, SocketFlags.None,
  84. null, req_callback, req_result) {}
  85. // For Connect
  86. public Worker(Socket req_sock, EndPoint req_endpoint,
  87. AsyncCallback req_callback,
  88. SocketAsyncResult req_result)
  89. : this(req_sock, null, 0, 0, SocketFlags.None,
  90. req_endpoint, req_callback,
  91. req_result) {}
  92. // For Receive and Send
  93. public Worker(Socket req_sock, byte[] req_buffer,
  94. int req_offset, int req_size,
  95. SocketFlags req_sockflags,
  96. AsyncCallback req_callback,
  97. SocketAsyncResult req_result)
  98. : this(req_sock, req_buffer, req_offset,
  99. req_size, req_sockflags, null,
  100. req_callback, req_result) {}
  101. // For ReceiveFrom and SendTo
  102. public Worker(Socket req_sock, byte[] req_buffer,
  103. int req_offset, int req_size,
  104. SocketFlags req_sockflags,
  105. EndPoint req_endpoint,
  106. AsyncCallback req_callback,
  107. SocketAsyncResult req_result) {
  108. socket=req_sock;
  109. buffer=req_buffer;
  110. offset=req_offset;
  111. size=req_size;
  112. sockflags=req_sockflags;
  113. endpoint=req_endpoint;
  114. callback=req_callback;
  115. result=req_result;
  116. }
  117. private void End() {
  118. ((ManualResetEvent)result.AsyncWaitHandle).Set();
  119. callback(result);
  120. result.IsCompleted=true;
  121. }
  122. public void Accept() {
  123. lock(result) {
  124. acc_socket=socket.Accept();
  125. End();
  126. }
  127. }
  128. public void Connect() {
  129. lock(result) {
  130. socket.Connect(endpoint);
  131. End();
  132. }
  133. }
  134. public void Receive() {
  135. lock(result) {
  136. total=socket.Receive(buffer, offset,
  137. size, sockflags);
  138. End();
  139. }
  140. }
  141. public void ReceiveFrom() {
  142. lock(result) {
  143. total=socket.ReceiveFrom(buffer,
  144. offset, size,
  145. sockflags,
  146. ref endpoint);
  147. End();
  148. }
  149. }
  150. public void Send() {
  151. lock(result) {
  152. total=socket.Send(buffer, offset, size,
  153. sockflags);
  154. End();
  155. }
  156. }
  157. public void SendTo() {
  158. lock(result) {
  159. total=socket.SendTo(buffer, offset,
  160. size, sockflags,
  161. endpoint);
  162. End();
  163. }
  164. }
  165. public EndPoint EndPoint {
  166. get {
  167. return(endpoint);
  168. }
  169. }
  170. public Socket Socket {
  171. get {
  172. return(acc_socket);
  173. }
  174. }
  175. public int Total {
  176. get {
  177. return(total);
  178. }
  179. }
  180. }
  181. /* the field "socket" is looked up by name by the runtime */
  182. private IntPtr socket;
  183. private AddressFamily address_family;
  184. private SocketType socket_type;
  185. private ProtocolType protocol_type;
  186. private bool blocking=true;
  187. /* When true, the socket was connected at the time of
  188. * the last IO operation
  189. */
  190. private bool connected=false;
  191. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  192. private extern static void Select_internal(ref Socket[] read,
  193. ref Socket[] write,
  194. ref Socket[] err,
  195. int timeout);
  196. public static void Select(IList read_list, IList write_list,
  197. IList err_list, int time_us) {
  198. if(read_list==null &&
  199. write_list==null &&
  200. err_list==null) {
  201. throw new ArgumentNullException();
  202. }
  203. int read_count, write_count, err_count;
  204. if(read_list!=null) {
  205. read_count=read_list.Count;
  206. } else {
  207. read_count=0;
  208. }
  209. if(write_list!=null) {
  210. write_count=write_list.Count;
  211. } else {
  212. write_count=0;
  213. }
  214. if(err_list!=null) {
  215. err_count=err_list.Count;
  216. } else {
  217. err_count=0;
  218. }
  219. Socket[] read_arr=new Socket[read_count];
  220. Socket[] write_arr=new Socket[write_count];
  221. Socket[] err_arr=new Socket[err_count];
  222. int i;
  223. if(read_list!=null) {
  224. i=0;
  225. foreach (Socket s in read_list) {
  226. read_arr[i]=s;
  227. i++;
  228. }
  229. }
  230. if(write_list!=null) {
  231. i=0;
  232. foreach (Socket s in write_list) {
  233. write_arr[i]=s;
  234. i++;
  235. }
  236. }
  237. if(err_list!=null) {
  238. i=0;
  239. foreach (Socket s in err_list) {
  240. err_arr[i]=s;
  241. i++;
  242. }
  243. }
  244. Select_internal(ref read_arr, ref write_arr,
  245. ref err_arr, time_us);
  246. if(read_list!=null) {
  247. read_list.Clear();
  248. for(i=0; i<read_arr.Length; i++) {
  249. read_list.Add(read_arr[i]);
  250. }
  251. }
  252. if(write_list!=null) {
  253. write_list.Clear();
  254. for(i=0; i<write_arr.Length; i++) {
  255. write_list.Add(write_arr[i]);
  256. }
  257. }
  258. if(err_list!=null) {
  259. err_list.Clear();
  260. for(i=0; i<err_arr.Length; i++) {
  261. err_list.Add(err_arr[i]);
  262. }
  263. }
  264. }
  265. // private constructor used by Accept, which already
  266. // has a socket handle to use
  267. private Socket(AddressFamily family, SocketType type,
  268. ProtocolType proto, IntPtr sock) {
  269. address_family=family;
  270. socket_type=type;
  271. protocol_type=proto;
  272. socket=sock;
  273. connected=true;
  274. }
  275. // Creates a new system socket, returning the handle
  276. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  277. private extern IntPtr Socket_internal(AddressFamily family,
  278. SocketType type,
  279. ProtocolType proto);
  280. public Socket(AddressFamily family, SocketType type,
  281. ProtocolType proto) {
  282. address_family=family;
  283. socket_type=type;
  284. protocol_type=proto;
  285. socket=Socket_internal(family, type, proto);
  286. }
  287. public AddressFamily AddressFamily {
  288. get {
  289. return(address_family);
  290. }
  291. }
  292. // Returns the amount of data waiting to be read on socket
  293. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  294. private extern static int Available_internal(IntPtr socket);
  295. public int Available {
  296. get {
  297. return(Available_internal(socket));
  298. }
  299. }
  300. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  301. private extern static void Blocking_internal(IntPtr socket,
  302. bool block);
  303. public bool Blocking {
  304. get {
  305. return(blocking);
  306. }
  307. set {
  308. Blocking_internal(socket, value);
  309. blocking=value;
  310. }
  311. }
  312. public bool Connected {
  313. get {
  314. return(connected);
  315. }
  316. }
  317. public IntPtr Handle {
  318. get {
  319. return(socket);
  320. }
  321. }
  322. // Returns the local endpoint details in addr and port
  323. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  324. private extern static SocketAddress LocalEndPoint_internal(IntPtr socket);
  325. [MonoTODO("Support non-IP endpoints")]
  326. public EndPoint LocalEndPoint {
  327. get {
  328. SocketAddress sa;
  329. sa=LocalEndPoint_internal(socket);
  330. if(sa.Family==AddressFamily.InterNetwork) {
  331. // Stupidly, EndPoint.Create() is an
  332. // instance method
  333. return new IPEndPoint(0, 0).Create(sa);
  334. } else {
  335. throw new NotImplementedException();
  336. }
  337. }
  338. }
  339. public ProtocolType ProtocolType {
  340. get {
  341. return(protocol_type);
  342. }
  343. }
  344. // Returns the remote endpoint details in addr and port
  345. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  346. private extern static SocketAddress RemoteEndPoint_internal(IntPtr socket);
  347. [MonoTODO("Support non-IP endpoints")]
  348. public EndPoint RemoteEndPoint {
  349. get {
  350. SocketAddress sa;
  351. sa=RemoteEndPoint_internal(socket);
  352. if(sa.Family==AddressFamily.InterNetwork) {
  353. // Stupidly, EndPoint.Create() is an
  354. // instance method
  355. return new IPEndPoint(0, 0).Create(sa);
  356. } else {
  357. throw new NotImplementedException();
  358. }
  359. }
  360. }
  361. public SocketType SocketType {
  362. get {
  363. return(socket_type);
  364. }
  365. }
  366. // Creates a new system socket, returning the handle
  367. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  368. private extern static IntPtr Accept_internal(IntPtr sock);
  369. public Socket Accept() {
  370. IntPtr sock=Accept_internal(socket);
  371. return(new Socket(this.AddressFamily, this.SocketType,
  372. this.ProtocolType, sock));
  373. }
  374. public IAsyncResult BeginAccept(AsyncCallback callback,
  375. object state) {
  376. SocketAsyncResult req=new SocketAsyncResult(state);
  377. Worker worker=new Worker(this, callback, req);
  378. req.Worker=worker;
  379. Thread child=new Thread(new ThreadStart(worker.Accept));
  380. child.Start();
  381. return(req);
  382. }
  383. public IAsyncResult BeginConnect(EndPoint end_point,
  384. AsyncCallback callback,
  385. object state) {
  386. SocketAsyncResult req=new SocketAsyncResult(state);
  387. Worker worker=new Worker(this, end_point, callback,
  388. req);
  389. req.Worker=worker;
  390. Thread child=new Thread(new ThreadStart(worker.Connect));
  391. child.Start();
  392. return(req);
  393. }
  394. public IAsyncResult BeginReceive(byte[] buffer, int offset,
  395. int size,
  396. SocketFlags socket_flags,
  397. AsyncCallback callback,
  398. object state) {
  399. SocketAsyncResult req=new SocketAsyncResult(state);
  400. Worker worker=new Worker(this, buffer, offset, size,
  401. socket_flags, callback, req);
  402. req.Worker=worker;
  403. Thread child=new Thread(new ThreadStart(worker.Receive));
  404. child.Start();
  405. return(req);
  406. }
  407. public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset,
  408. int size,
  409. SocketFlags socket_flags,
  410. ref EndPoint remote_end,
  411. AsyncCallback callback,
  412. object state) {
  413. SocketAsyncResult req=new SocketAsyncResult(state);
  414. Worker worker=new Worker(this, buffer, offset, size,
  415. socket_flags, remote_end,
  416. callback, req);
  417. req.Worker=worker;
  418. Thread child=new Thread(new ThreadStart(worker.ReceiveFrom));
  419. child.Start();
  420. return(req);
  421. }
  422. public IAsyncResult BeginSend(byte[] buffer, int offset,
  423. int size,
  424. SocketFlags socket_flags,
  425. AsyncCallback callback,
  426. object state) {
  427. SocketAsyncResult req=new SocketAsyncResult(state);
  428. Worker worker=new Worker(this, buffer, offset, size,
  429. socket_flags, callback, req);
  430. req.Worker=worker;
  431. Thread child=new Thread(new ThreadStart(worker.Send));
  432. child.Start();
  433. return(req);
  434. }
  435. public IAsyncResult BeginSendTo(byte[] buffer, int offset,
  436. int size,
  437. SocketFlags socket_flags,
  438. EndPoint remote_end,
  439. AsyncCallback callback,
  440. object state) {
  441. SocketAsyncResult req=new SocketAsyncResult(state);
  442. Worker worker=new Worker(this, buffer, offset, size,
  443. socket_flags, remote_end,
  444. callback, req);
  445. req.Worker=worker;
  446. Thread child=new Thread(new ThreadStart(worker.SendTo));
  447. child.Start();
  448. return(req);
  449. }
  450. // Creates a new system socket, returning the handle
  451. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  452. private extern static void Bind_internal(IntPtr sock,
  453. SocketAddress sa);
  454. public void Bind(EndPoint local_end) {
  455. if(local_end==null) {
  456. throw new ArgumentNullException();
  457. }
  458. Bind_internal(socket, local_end.Serialize());
  459. }
  460. // Closes the socket
  461. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  462. private extern static void Close_internal(IntPtr socket);
  463. public void Close() {
  464. this.Dispose();
  465. }
  466. // Connects to the remote address
  467. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  468. private extern static void Connect_internal(IntPtr sock,
  469. SocketAddress sa);
  470. public void Connect(EndPoint remote_end) {
  471. if(remote_end==null) {
  472. throw new ArgumentNullException();
  473. }
  474. Connect_internal(socket, remote_end.Serialize());
  475. connected=true;
  476. }
  477. public Socket EndAccept(IAsyncResult result) {
  478. SocketAsyncResult req=(SocketAsyncResult)result;
  479. result.AsyncWaitHandle.WaitOne();
  480. return(req.Worker.Socket);
  481. }
  482. public void EndConnect(IAsyncResult result) {
  483. SocketAsyncResult req=(SocketAsyncResult)result;
  484. result.AsyncWaitHandle.WaitOne();
  485. }
  486. public int EndReceive(IAsyncResult result) {
  487. SocketAsyncResult req=(SocketAsyncResult)result;
  488. result.AsyncWaitHandle.WaitOne();
  489. return(req.Worker.Total);
  490. }
  491. public int EndReceiveFrom(IAsyncResult result,
  492. ref EndPoint end_point) {
  493. SocketAsyncResult req=(SocketAsyncResult)result;
  494. result.AsyncWaitHandle.WaitOne();
  495. end_point=req.Worker.EndPoint;
  496. return(req.Worker.Total);
  497. }
  498. public int EndSend(IAsyncResult result) {
  499. SocketAsyncResult req=(SocketAsyncResult)result;
  500. result.AsyncWaitHandle.WaitOne();
  501. return(req.Worker.Total);
  502. }
  503. public int EndSendTo(IAsyncResult result) {
  504. SocketAsyncResult req=(SocketAsyncResult)result;
  505. result.AsyncWaitHandle.WaitOne();
  506. return(req.Worker.Total);
  507. }
  508. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  509. private extern static void GetSocketOption_obj_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, out object obj_val);
  510. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  511. private extern static void GetSocketOption_arr_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val);
  512. public object GetSocketOption(SocketOptionLevel level,
  513. SocketOptionName name) {
  514. object obj_val;
  515. GetSocketOption_obj_internal(socket, level, name,
  516. out obj_val);
  517. if(name==SocketOptionName.Linger) {
  518. return((LingerOption)obj_val);
  519. } else if (name==SocketOptionName.AddMembership ||
  520. name==SocketOptionName.DropMembership) {
  521. return((MulticastOption)obj_val);
  522. } else {
  523. return((int)obj_val);
  524. }
  525. }
  526. public void GetSocketOption(SocketOptionLevel level,
  527. SocketOptionName name,
  528. byte[] opt_value) {
  529. int opt_value_len=opt_value.Length;
  530. GetSocketOption_arr_internal(socket, level, name,
  531. ref opt_value);
  532. }
  533. public byte[] GetSocketOption(SocketOptionLevel level,
  534. SocketOptionName name,
  535. int length) {
  536. byte[] byte_val=new byte[length];
  537. GetSocketOption_arr_internal(socket, level, name,
  538. ref byte_val);
  539. return(byte_val);
  540. }
  541. [MonoTODO("Totally undocumented")]
  542. public int IOControl(int ioctl_code, byte[] in_value,
  543. byte[] out_value) {
  544. throw new NotImplementedException();
  545. }
  546. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  547. private extern static void Listen_internal(IntPtr sock,
  548. int backlog);
  549. public void Listen(int backlog) {
  550. Listen_internal(socket, backlog);
  551. }
  552. /* The docs for Poll() are a bit lightweight too, but
  553. * it seems to be just a simple wrapper around Select.
  554. */
  555. public bool Poll(int time_us, SelectMode mode) {
  556. ArrayList socketlist=new ArrayList(1);
  557. socketlist.Add(this);
  558. switch(mode) {
  559. case SelectMode.SelectError:
  560. Select(null, null, socketlist, time_us);
  561. break;
  562. case SelectMode.SelectRead:
  563. Select(socketlist, null, null, time_us);
  564. break;
  565. case SelectMode.SelectWrite:
  566. Select(null, socketlist, null, time_us);
  567. break;
  568. default:
  569. throw new NotSupportedException();
  570. }
  571. if(socketlist.Contains(this)) {
  572. return(true);
  573. } else {
  574. return(false);
  575. }
  576. }
  577. public int Receive(byte[] buf) {
  578. return(Receive(buf, 0, buf.Length, SocketFlags.None));
  579. }
  580. public int Receive(byte[] buf, SocketFlags flags) {
  581. return(Receive(buf, 0, buf.Length, flags));
  582. }
  583. public int Receive(byte[] buf, int size, SocketFlags flags) {
  584. return(Receive(buf, 0, size, flags));
  585. }
  586. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  587. private extern static int Receive_internal(IntPtr sock,
  588. byte[] buffer,
  589. int offset,
  590. int count,
  591. SocketFlags flags);
  592. public int Receive(byte[] buf, int offset, int size,
  593. SocketFlags flags) {
  594. if(buf==null) {
  595. throw new ArgumentNullException("buffer is null");
  596. }
  597. if(offset<0 || offset >= buf.Length) {
  598. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  599. }
  600. if(offset+size<0 || offset+size > buf.Length) {
  601. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  602. }
  603. int ret;
  604. try {
  605. ret=Receive_internal(socket, buf, offset,
  606. size, flags);
  607. } catch(SocketException) {
  608. connected=false;
  609. throw;
  610. }
  611. connected=true;
  612. return(ret);
  613. }
  614. public int ReceiveFrom(byte[] buf, ref EndPoint remote_end) {
  615. return(ReceiveFrom(buf, 0, buf.Length,
  616. SocketFlags.None, ref remote_end));
  617. }
  618. public int ReceiveFrom(byte[] buf, SocketFlags flags,
  619. ref EndPoint remote_end) {
  620. return(ReceiveFrom(buf, 0, buf.Length, flags,
  621. ref remote_end));
  622. }
  623. public int ReceiveFrom(byte[] buf, int size, SocketFlags flags,
  624. ref EndPoint remote_end) {
  625. return(ReceiveFrom(buf, 0, size, flags,
  626. ref remote_end));
  627. }
  628. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  629. private extern static int RecvFrom_internal(IntPtr sock,
  630. byte[] buffer,
  631. int offset,
  632. int count,
  633. SocketFlags flags,
  634. ref SocketAddress sockaddr);
  635. public int ReceiveFrom(byte[] buf, int offset, int size,
  636. SocketFlags flags,
  637. ref EndPoint remote_end) {
  638. if(buf==null) {
  639. throw new ArgumentNullException("buffer is null");
  640. }
  641. if(remote_end==null) {
  642. throw new ArgumentNullException("remote endpoint is null");
  643. }
  644. if(offset<0 || offset>=buf.Length) {
  645. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  646. }
  647. if(offset+size<0 || offset+size>buf.Length) {
  648. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  649. }
  650. SocketAddress sockaddr=remote_end.Serialize();
  651. int count;
  652. try {
  653. count=RecvFrom_internal(socket, buf, offset,
  654. size, flags,
  655. ref sockaddr);
  656. } catch(SocketException) {
  657. connected=false;
  658. throw;
  659. }
  660. connected=true;
  661. // Stupidly, EndPoint.Create() is an
  662. // instance method
  663. remote_end=remote_end.Create(sockaddr);
  664. return(count);
  665. }
  666. public int Send(byte[] buf) {
  667. return(Send(buf, 0, buf.Length, SocketFlags.None));
  668. }
  669. public int Send(byte[] buf, SocketFlags flags) {
  670. return(Send(buf, 0, buf.Length, flags));
  671. }
  672. public int Send(byte[] buf, int size, SocketFlags flags) {
  673. return(Send(buf, 0, size, flags));
  674. }
  675. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  676. private extern static int Send_internal(IntPtr sock,
  677. byte[] buf, int offset,
  678. int count,
  679. SocketFlags flags);
  680. public int Send (byte[] buf, int offset, int size, SocketFlags flags)
  681. {
  682. if (buf == null)
  683. throw new ArgumentNullException ("buffer");
  684. if (offset < 0 || offset > buf.Length)
  685. throw new ArgumentOutOfRangeException ("offset");
  686. if (size < 0 || offset + size > buf.Length)
  687. throw new ArgumentOutOfRangeException ("size");
  688. if (size == 0)
  689. return 0;
  690. int ret;
  691. try {
  692. ret = Send_internal (socket, buf, offset, size, flags);
  693. } catch (SocketException) {
  694. connected = false;
  695. throw;
  696. }
  697. connected = true;
  698. return ret;
  699. }
  700. public int SendTo(byte[] buffer, EndPoint remote_end) {
  701. return(SendTo(buffer, 0, buffer.Length,
  702. SocketFlags.None, remote_end));
  703. }
  704. public int SendTo(byte[] buffer, SocketFlags flags,
  705. EndPoint remote_end) {
  706. return(SendTo(buffer, 0, buffer.Length, flags,
  707. remote_end));
  708. }
  709. public int SendTo(byte[] buffer, int size, SocketFlags flags,
  710. EndPoint remote_end) {
  711. return(SendTo(buffer, size, buffer.Length, flags,
  712. remote_end));
  713. }
  714. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  715. private extern static int SendTo_internal(IntPtr sock,
  716. byte[] buffer,
  717. int offset,
  718. int count,
  719. SocketFlags flags,
  720. SocketAddress sa);
  721. public int SendTo(byte[] buffer, int offset, int size,
  722. SocketFlags flags, EndPoint remote_end) {
  723. if(buffer==null) {
  724. throw new ArgumentNullException("buffer is null");
  725. }
  726. if(remote_end==null) {
  727. throw new ArgumentNullException("remote endpoint is null");
  728. }
  729. if(offset<0 || offset>=buffer.Length) {
  730. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  731. }
  732. if(offset+size<0 || offset+size>buffer.Length) {
  733. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  734. }
  735. SocketAddress sockaddr=remote_end.Serialize();
  736. int ret;
  737. try {
  738. ret=SendTo_internal(socket, buffer, offset,
  739. size, flags, sockaddr);
  740. }
  741. catch(SocketException) {
  742. connected=false;
  743. throw;
  744. }
  745. connected=true;
  746. return(ret);
  747. }
  748. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  749. private extern static void SetSocketOption_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, object obj_val, byte[] byte_val, int int_val);
  750. public void SetSocketOption(SocketOptionLevel level,
  751. SocketOptionName name,
  752. byte[] opt_value) {
  753. SetSocketOption_internal(socket, level, name, null,
  754. opt_value, 0);
  755. }
  756. public void SetSocketOption(SocketOptionLevel level,
  757. SocketOptionName name,
  758. int opt_value) {
  759. SetSocketOption_internal(socket, level, name, null,
  760. null, opt_value);
  761. }
  762. public void SetSocketOption(SocketOptionLevel level,
  763. SocketOptionName name,
  764. object opt_value) {
  765. if(opt_value==null) {
  766. throw new ArgumentNullException();
  767. }
  768. /* Passing a bool as the third parameter to
  769. * SetSocketOption causes this overload to be
  770. * used when in fact we want to pass the value
  771. * to the runtime as an int.
  772. */
  773. if(opt_value is System.Boolean) {
  774. bool bool_val=(bool)opt_value;
  775. /* Stupid casting rules :-( */
  776. if(bool_val==true) {
  777. SetSocketOption_internal(socket, level,
  778. name, null,
  779. null, 1);
  780. } else {
  781. SetSocketOption_internal(socket, level,
  782. name, null,
  783. null, 0);
  784. }
  785. } else {
  786. SetSocketOption_internal(socket, level, name,
  787. opt_value, null, 0);
  788. }
  789. }
  790. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  791. private extern static void Shutdown_internal(IntPtr socket, SocketShutdown how);
  792. public void Shutdown(SocketShutdown how) {
  793. Shutdown_internal(socket, how);
  794. }
  795. private bool disposed = false;
  796. protected virtual void Dispose(bool explicitDisposing) {
  797. // Check to see if Dispose has already been called
  798. if(!this.disposed) {
  799. // If this is a call to Dispose,
  800. // dispose all managed resources.
  801. if(explicitDisposing) {
  802. // Free up stuff here
  803. }
  804. // Release unmanaged resources
  805. this.disposed=true;
  806. connected=false;
  807. Close_internal(socket);
  808. }
  809. }
  810. public void Dispose() {
  811. Dispose(true);
  812. // Take yourself off the Finalization queue
  813. GC.SuppressFinalize(this);
  814. }
  815. ~Socket () {
  816. Dispose(false);
  817. }
  818. }
  819. }