Socket.cs 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  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. using System.Reflection;
  16. using System.IO;
  17. namespace System.Net.Sockets
  18. {
  19. public class Socket : IDisposable
  20. {
  21. private sealed class SocketAsyncResult: IAsyncResult
  22. {
  23. private object state;
  24. private WaitHandle waithandle;
  25. private bool completed_sync, completed;
  26. private Worker worker;
  27. private Exception delayedException = null;
  28. public SocketAsyncResult(object state) {
  29. this.state=state;
  30. waithandle=new ManualResetEvent(false);
  31. completed_sync=completed=false;
  32. }
  33. public void SetDelayedException (Exception e) {
  34. delayedException = e;
  35. }
  36. public void CheckIfThrowDelayedException () {
  37. if (delayedException != null)
  38. throw delayedException;
  39. }
  40. public object AsyncState {
  41. get {
  42. return(state);
  43. }
  44. }
  45. public WaitHandle AsyncWaitHandle {
  46. get {
  47. return(waithandle);
  48. }
  49. set {
  50. waithandle=value;
  51. }
  52. }
  53. public bool CompletedSynchronously {
  54. get {
  55. return(completed_sync);
  56. }
  57. }
  58. public bool IsCompleted {
  59. get {
  60. return(completed);
  61. }
  62. set {
  63. completed=value;
  64. }
  65. }
  66. public Worker Worker {
  67. get {
  68. return(worker);
  69. }
  70. set {
  71. worker=value;
  72. }
  73. }
  74. }
  75. private sealed class Worker
  76. {
  77. private AsyncCallback callback;
  78. private SocketAsyncResult result;
  79. private Socket socket;
  80. // Parameters
  81. private EndPoint endpoint; // Connect,ReceiveFrom,SendTo
  82. private byte[] buffer; // Receive,ReceiveFrom,Send,SendTo
  83. private int offset; // Receive,ReceiveFrom,Send,SendTo
  84. private int size; // Receive,ReceiveFrom,Send,SendTo
  85. private SocketFlags sockflags; // Receive,ReceiveFrom,Send,SendTo
  86. // Return values
  87. private Socket acc_socket;
  88. private int total;
  89. // For Accept
  90. public Worker(Socket req_sock,
  91. AsyncCallback req_callback,
  92. SocketAsyncResult req_result)
  93. : this(req_sock, null, 0, 0, SocketFlags.None,
  94. null, req_callback, req_result) {}
  95. // For Connect
  96. public Worker(Socket req_sock, EndPoint req_endpoint,
  97. AsyncCallback req_callback,
  98. SocketAsyncResult req_result)
  99. : this(req_sock, null, 0, 0, SocketFlags.None,
  100. req_endpoint, req_callback,
  101. req_result) {}
  102. // For Receive and Send
  103. public Worker(Socket req_sock, byte[] req_buffer,
  104. int req_offset, int req_size,
  105. SocketFlags req_sockflags,
  106. AsyncCallback req_callback,
  107. SocketAsyncResult req_result)
  108. : this(req_sock, req_buffer, req_offset,
  109. req_size, req_sockflags, null,
  110. req_callback, req_result) {}
  111. // For ReceiveFrom and SendTo
  112. public Worker(Socket req_sock, byte[] req_buffer,
  113. int req_offset, int req_size,
  114. SocketFlags req_sockflags,
  115. EndPoint req_endpoint,
  116. AsyncCallback req_callback,
  117. SocketAsyncResult req_result) {
  118. socket=req_sock;
  119. buffer=req_buffer;
  120. offset=req_offset;
  121. size=req_size;
  122. sockflags=req_sockflags;
  123. endpoint=req_endpoint;
  124. callback=req_callback;
  125. result=req_result;
  126. }
  127. private void End() {
  128. ((ManualResetEvent)result.AsyncWaitHandle).Set();
  129. result.IsCompleted=true;
  130. if (callback != null)
  131. callback(result);
  132. }
  133. public void Accept() {
  134. lock(result) {
  135. try {
  136. acc_socket=socket.Accept();
  137. } catch (Exception e) {
  138. result.SetDelayedException(e);
  139. }
  140. End();
  141. }
  142. }
  143. public void Connect() {
  144. lock(result) {
  145. if (socket.Blocking) {
  146. try {
  147. socket.Connect(endpoint);
  148. } catch (Exception e) {
  149. result.SetDelayedException(e);
  150. }
  151. End ();
  152. return;
  153. }
  154. SocketException rethrow = null;
  155. try {
  156. socket.Connect (endpoint);
  157. } catch (SocketException e) {
  158. //WSAEINPROGRESS
  159. if (e.NativeErrorCode != 10036) {
  160. result.SetDelayedException(e);
  161. End ();
  162. return;
  163. }
  164. socket.Poll (-1, SelectMode.SelectWrite);
  165. try {
  166. socket.Connect (endpoint);
  167. } catch (SocketException e2) {
  168. rethrow = e2;
  169. }
  170. }
  171. if (rethrow != null)
  172. result.SetDelayedException(rethrow);
  173. End ();
  174. }
  175. }
  176. public void Receive() {
  177. lock(result) {
  178. if (socket.Blocking) {
  179. try {
  180. total=socket.Receive(buffer, offset,
  181. size, sockflags);
  182. } catch (Exception e) {
  183. result.SetDelayedException(e);
  184. }
  185. End();
  186. return;
  187. }
  188. SocketException rethrow = null;
  189. try {
  190. total = socket.Receive (buffer, offset, size, sockflags);
  191. } catch (SocketException e) {
  192. //WSAEWOULDBLOCK
  193. if (e.NativeErrorCode != 10035) {
  194. result.SetDelayedException(e);
  195. End ();
  196. return;
  197. }
  198. socket.Poll (-1, SelectMode.SelectRead);
  199. try {
  200. total = socket.Receive (buffer, offset, size, sockflags);
  201. } catch (SocketException e2) {
  202. rethrow = e2;
  203. }
  204. }
  205. if (rethrow != null)
  206. result.SetDelayedException(rethrow);
  207. End ();
  208. }
  209. }
  210. public void ReceiveFrom() {
  211. lock(result) {
  212. try {
  213. total=socket.ReceiveFrom(buffer,
  214. offset, size,
  215. sockflags,
  216. ref endpoint);
  217. } catch (Exception e) {
  218. result.SetDelayedException(e);
  219. }
  220. End();
  221. }
  222. }
  223. public void Send() {
  224. lock(result) {
  225. try {
  226. total=socket.Send(buffer, offset, size,
  227. sockflags);
  228. } catch (Exception e) {
  229. result.SetDelayedException(e);
  230. }
  231. End();
  232. }
  233. }
  234. public void SendTo() {
  235. lock(result) {
  236. try {
  237. total=socket.SendTo(buffer, offset,
  238. size, sockflags,
  239. endpoint);
  240. } catch (Exception e) {
  241. result.SetDelayedException(e);
  242. }
  243. End();
  244. }
  245. }
  246. public EndPoint EndPoint {
  247. get {
  248. return(endpoint);
  249. }
  250. }
  251. public Socket Socket {
  252. get {
  253. return(acc_socket);
  254. }
  255. }
  256. public int Total {
  257. get {
  258. return(total);
  259. }
  260. }
  261. }
  262. /* the field "socket" is looked up by name by the runtime */
  263. private IntPtr socket;
  264. private AddressFamily address_family;
  265. private SocketType socket_type;
  266. private ProtocolType protocol_type;
  267. private bool blocking=true;
  268. private int pendingEnds;
  269. private int closeDelayed;
  270. /*
  271. * These two fields are looked up by name by the runtime, don't change
  272. * their name without also updating the runtime code.
  273. */
  274. private static int ipv4Supported = -1, ipv6Supported = -1;
  275. /* When true, the socket was connected at the time of
  276. * the last IO operation
  277. */
  278. private bool connected=false;
  279. /* true if we called Close_internal */
  280. private bool closed;
  281. /* Used in LocalEndPoint and RemoteEndPoint if the
  282. * Mono.Posix assembly is available
  283. */
  284. private static object unixendpoint=null;
  285. private static Type unixendpointtype=null;
  286. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  287. private extern static void Select_internal(ref Socket[] read,
  288. ref Socket[] write,
  289. ref Socket[] err,
  290. int timeout);
  291. public static void Select(IList read_list, IList write_list,
  292. IList err_list, int time_us) {
  293. if(read_list==null &&
  294. write_list==null &&
  295. err_list==null) {
  296. throw new ArgumentNullException();
  297. }
  298. int read_count = 0, write_count = 0, err_count = 0;
  299. Socket[] read_arr = null;
  300. Socket[] write_arr = null;
  301. Socket[] err_arr = null;
  302. if (read_list!=null)
  303. read_count=read_list.Count;
  304. if (read_count != 0)
  305. read_arr=new Socket[read_count];
  306. if (write_list!=null)
  307. write_count=write_list.Count;
  308. if (write_count != 0)
  309. write_arr=new Socket[write_count];
  310. if (err_list!=null)
  311. err_count=err_list.Count;
  312. if (err_count != 0)
  313. err_arr=new Socket[err_count];
  314. int i;
  315. if (read_count != 0) {
  316. i=0;
  317. foreach (Socket s in read_list) {
  318. read_arr[i]=s;
  319. i++;
  320. }
  321. }
  322. if (write_count != 0) {
  323. i=0;
  324. foreach (Socket s in write_list) {
  325. write_arr[i]=s;
  326. i++;
  327. }
  328. }
  329. if (err_count != 0) {
  330. i=0;
  331. foreach (Socket s in err_list) {
  332. err_arr[i]=s;
  333. i++;
  334. }
  335. }
  336. Select_internal(ref read_arr, ref write_arr,
  337. ref err_arr, time_us);
  338. if(read_list!=null) {
  339. read_list.Clear();
  340. for(i=0; i<read_arr.Length; i++) {
  341. read_list.Add(read_arr[i]);
  342. }
  343. }
  344. if(write_list!=null) {
  345. write_list.Clear();
  346. for(i=0; i<write_arr.Length; i++) {
  347. write_list.Add(write_arr[i]);
  348. }
  349. }
  350. if(err_list!=null) {
  351. err_list.Clear();
  352. for(i=0; i<err_arr.Length; i++) {
  353. err_list.Add(err_arr[i]);
  354. }
  355. }
  356. }
  357. static Socket() {
  358. Assembly ass;
  359. try {
  360. ass=Assembly.Load("Mono.Posix");
  361. } catch (FileNotFoundException) {
  362. return;
  363. }
  364. unixendpointtype=ass.GetType("Mono.Posix.UnixEndPoint");
  365. /* The endpoint Create() method is an instance
  366. * method :-(
  367. */
  368. Type[] arg_types=new Type[1];
  369. arg_types[0]=typeof(string);
  370. ConstructorInfo cons=unixendpointtype.GetConstructor(arg_types);
  371. object[] args=new object[1];
  372. args[0]="";
  373. unixendpoint=cons.Invoke(args);
  374. }
  375. // private constructor used by Accept, which already
  376. // has a socket handle to use
  377. private Socket(AddressFamily family, SocketType type,
  378. ProtocolType proto, IntPtr sock) {
  379. address_family=family;
  380. socket_type=type;
  381. protocol_type=proto;
  382. socket=sock;
  383. connected=true;
  384. }
  385. // Creates a new system socket, returning the handle
  386. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  387. private extern IntPtr Socket_internal(AddressFamily family,
  388. SocketType type,
  389. ProtocolType proto);
  390. public Socket(AddressFamily family, SocketType type,
  391. ProtocolType proto) {
  392. address_family=family;
  393. socket_type=type;
  394. protocol_type=proto;
  395. socket=Socket_internal(family, type, proto);
  396. }
  397. public AddressFamily AddressFamily {
  398. get {
  399. return(address_family);
  400. }
  401. }
  402. // Returns the amount of data waiting to be read on socket
  403. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  404. private extern static int Available_internal(IntPtr socket);
  405. public int Available {
  406. get {
  407. if (disposed && closed)
  408. throw new ObjectDisposedException (GetType ().ToString ());
  409. return(Available_internal(socket));
  410. }
  411. }
  412. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  413. private extern static void Blocking_internal(IntPtr socket,
  414. bool block);
  415. public bool Blocking {
  416. get {
  417. return(blocking);
  418. }
  419. set {
  420. Blocking_internal(socket, value);
  421. blocking=value;
  422. }
  423. }
  424. public bool Connected {
  425. get {
  426. return(connected);
  427. }
  428. }
  429. public IntPtr Handle {
  430. get {
  431. return(socket);
  432. }
  433. }
  434. // Returns the local endpoint details in addr and port
  435. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  436. private extern static SocketAddress LocalEndPoint_internal(IntPtr socket);
  437. [MonoTODO("Support non-IP endpoints")]
  438. public EndPoint LocalEndPoint {
  439. get {
  440. if (disposed && closed)
  441. throw new ObjectDisposedException (GetType ().ToString ());
  442. SocketAddress sa;
  443. sa=LocalEndPoint_internal(socket);
  444. if(sa.Family==AddressFamily.InterNetwork || sa.Family==AddressFamily.InterNetworkV6) {
  445. // Stupidly, EndPoint.Create() is an
  446. // instance method
  447. return new IPEndPoint(0, 0).Create(sa);
  448. } else if (sa.Family==AddressFamily.Unix &&
  449. unixendpoint!=null) {
  450. return((EndPoint)unixendpointtype.InvokeMember("Create", BindingFlags.InvokeMethod|BindingFlags.Instance|BindingFlags.Public, null, unixendpoint, new object[] {sa}));
  451. } else {
  452. throw new NotImplementedException();
  453. }
  454. }
  455. }
  456. public ProtocolType ProtocolType {
  457. get {
  458. return(protocol_type);
  459. }
  460. }
  461. // Returns the remote endpoint details in addr and port
  462. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  463. private extern static SocketAddress RemoteEndPoint_internal(IntPtr socket);
  464. [MonoTODO("Support non-IP endpoints")]
  465. public EndPoint RemoteEndPoint {
  466. get {
  467. if (disposed && closed)
  468. throw new ObjectDisposedException (GetType ().ToString ());
  469. SocketAddress sa;
  470. sa=RemoteEndPoint_internal(socket);
  471. if(sa.Family==AddressFamily.InterNetwork || sa.Family==AddressFamily.InterNetworkV6 ) {
  472. // Stupidly, EndPoint.Create() is an
  473. // instance method
  474. return new IPEndPoint(0, 0).Create(sa);
  475. } else if (sa.Family==AddressFamily.Unix &&
  476. unixendpoint!=null) {
  477. return((EndPoint)unixendpointtype.InvokeMember("Create", BindingFlags.InvokeMethod|BindingFlags.Instance|BindingFlags.Public, null, unixendpoint, new object[] {sa}));
  478. } else {
  479. throw new NotImplementedException();
  480. }
  481. }
  482. }
  483. public SocketType SocketType {
  484. get {
  485. return(socket_type);
  486. }
  487. }
  488. #if NET_1_1
  489. public static bool SupportsIPv4 {
  490. get {
  491. CheckProtocolSupport();
  492. return ipv4Supported == 1;
  493. }
  494. }
  495. public static bool SupportsIPv6 {
  496. get {
  497. CheckProtocolSupport();
  498. return ipv6Supported == 1;
  499. }
  500. }
  501. #else
  502. internal static bool SupportsIPv4
  503. {
  504. get
  505. {
  506. return true;
  507. }
  508. }
  509. internal static bool SupportsIPv6
  510. {
  511. get
  512. {
  513. return false;
  514. }
  515. }
  516. #endif
  517. internal static void CheckProtocolSupport()
  518. {
  519. if(ipv4Supported == -1) {
  520. try {
  521. Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  522. tmp.Close();
  523. ipv4Supported = 1;
  524. }
  525. catch {
  526. ipv4Supported = 0;
  527. }
  528. }
  529. if(ipv6Supported == -1) {
  530. NetConfig config = (NetConfig)System.Configuration.ConfigurationSettings.GetConfig("system.net/settings");
  531. if(config != null)
  532. ipv6Supported = config.ipv6Enabled?-1:0;
  533. if(ipv6Supported != 0) {
  534. try {
  535. Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
  536. tmp.Close();
  537. ipv6Supported = 1;
  538. }
  539. catch { }
  540. }
  541. }
  542. }
  543. // Creates a new system socket, returning the handle
  544. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  545. private extern static IntPtr Accept_internal(IntPtr sock);
  546. public Socket Accept() {
  547. if (disposed && closed)
  548. throw new ObjectDisposedException (GetType ().ToString ());
  549. IntPtr sock=Accept_internal(socket);
  550. return(new Socket(this.AddressFamily, this.SocketType,
  551. this.ProtocolType, sock));
  552. }
  553. public IAsyncResult BeginAccept(AsyncCallback callback,
  554. object state) {
  555. if (disposed && closed)
  556. throw new ObjectDisposedException (GetType ().ToString ());
  557. Interlocked.Increment (ref pendingEnds);
  558. SocketAsyncResult req=new SocketAsyncResult(state);
  559. Worker worker=new Worker(this, callback, req);
  560. req.Worker=worker;
  561. Thread child=new Thread(new ThreadStart(worker.Accept));
  562. child.IsBackground = true;
  563. child.Start();
  564. return(req);
  565. }
  566. public IAsyncResult BeginConnect(EndPoint end_point,
  567. AsyncCallback callback,
  568. object state) {
  569. if (disposed && closed)
  570. throw new ObjectDisposedException (GetType ().ToString ());
  571. if (end_point == null)
  572. throw new ArgumentNullException ("end_point");
  573. Interlocked.Increment (ref pendingEnds);
  574. SocketAsyncResult req=new SocketAsyncResult(state);
  575. Worker worker=new Worker(this, end_point, callback,
  576. req);
  577. req.Worker=worker;
  578. Thread child=new Thread(new ThreadStart(worker.Connect));
  579. child.IsBackground = true;
  580. child.Start();
  581. return(req);
  582. }
  583. public IAsyncResult BeginReceive(byte[] buffer, int offset,
  584. int size,
  585. SocketFlags socket_flags,
  586. AsyncCallback callback,
  587. object state) {
  588. if (disposed && closed)
  589. throw new ObjectDisposedException (GetType ().ToString ());
  590. if (buffer == null)
  591. throw new ArgumentNullException ("buffer");
  592. if (offset < 0)
  593. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  594. if (size < 0)
  595. throw new ArgumentOutOfRangeException ("size must be >= 0");
  596. if (offset + size > buffer.Length)
  597. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  598. Interlocked.Increment (ref pendingEnds);
  599. SocketAsyncResult req=new SocketAsyncResult(state);
  600. Worker worker=new Worker(this, buffer, offset, size,
  601. socket_flags, callback, req);
  602. req.Worker=worker;
  603. Thread child=new Thread(new ThreadStart(worker.Receive));
  604. child.IsBackground = true;
  605. child.Start();
  606. return(req);
  607. }
  608. public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset,
  609. int size,
  610. SocketFlags socket_flags,
  611. ref EndPoint remote_end,
  612. AsyncCallback callback,
  613. object state) {
  614. if (disposed && closed)
  615. throw new ObjectDisposedException (GetType ().ToString ());
  616. if (buffer == null)
  617. throw new ArgumentNullException ("buffer");
  618. if (offset < 0)
  619. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  620. if (size < 0)
  621. throw new ArgumentOutOfRangeException ("size must be >= 0");
  622. if (offset + size > buffer.Length)
  623. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  624. Interlocked.Increment (ref pendingEnds);
  625. SocketAsyncResult req=new SocketAsyncResult(state);
  626. Worker worker=new Worker(this, buffer, offset, size,
  627. socket_flags, remote_end,
  628. callback, req);
  629. req.Worker=worker;
  630. Thread child=new Thread(new ThreadStart(worker.ReceiveFrom));
  631. child.IsBackground = true;
  632. child.Start();
  633. return(req);
  634. }
  635. public IAsyncResult BeginSend(byte[] buffer, int offset,
  636. int size,
  637. SocketFlags socket_flags,
  638. AsyncCallback callback,
  639. object state) {
  640. if (disposed && closed)
  641. throw new ObjectDisposedException (GetType ().ToString ());
  642. if (buffer == null)
  643. throw new ArgumentNullException ("buffer");
  644. if (offset < 0)
  645. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  646. if (size < 0)
  647. throw new ArgumentOutOfRangeException ("size must be >= 0");
  648. if (offset + size > buffer.Length)
  649. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  650. Interlocked.Increment (ref pendingEnds);
  651. SocketAsyncResult req=new SocketAsyncResult(state);
  652. Worker worker=new Worker(this, buffer, offset, size,
  653. socket_flags, callback, req);
  654. req.Worker=worker;
  655. Thread child=new Thread(new ThreadStart(worker.Send));
  656. child.IsBackground = true;
  657. child.Start();
  658. return(req);
  659. }
  660. public IAsyncResult BeginSendTo(byte[] buffer, int offset,
  661. int size,
  662. SocketFlags socket_flags,
  663. EndPoint remote_end,
  664. AsyncCallback callback,
  665. object state) {
  666. if (disposed && closed)
  667. throw new ObjectDisposedException (GetType ().ToString ());
  668. if (buffer == null)
  669. throw new ArgumentNullException ("buffer");
  670. if (offset < 0)
  671. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  672. if (size < 0)
  673. throw new ArgumentOutOfRangeException ("size must be >= 0");
  674. if (offset + size > buffer.Length)
  675. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  676. Interlocked.Increment (ref pendingEnds);
  677. SocketAsyncResult req=new SocketAsyncResult(state);
  678. Worker worker=new Worker(this, buffer, offset, size,
  679. socket_flags, remote_end,
  680. callback, req);
  681. req.Worker=worker;
  682. Thread child=new Thread(new ThreadStart(worker.SendTo));
  683. child.IsBackground = true;
  684. child.Start();
  685. return(req);
  686. }
  687. // Creates a new system socket, returning the handle
  688. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  689. private extern static void Bind_internal(IntPtr sock,
  690. SocketAddress sa);
  691. public void Bind(EndPoint local_end) {
  692. if (disposed && closed)
  693. throw new ObjectDisposedException (GetType ().ToString ());
  694. if(local_end==null) {
  695. throw new ArgumentNullException("local_end");
  696. }
  697. Bind_internal(socket, local_end.Serialize());
  698. }
  699. // Closes the socket
  700. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  701. private extern static void Close_internal(IntPtr socket);
  702. public void Close() {
  703. ((IDisposable) this).Dispose ();
  704. }
  705. // Connects to the remote address
  706. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  707. private extern static void Connect_internal(IntPtr sock,
  708. SocketAddress sa);
  709. public void Connect(EndPoint remote_end) {
  710. if (disposed && closed)
  711. throw new ObjectDisposedException (GetType ().ToString ());
  712. if(remote_end==null) {
  713. throw new ArgumentNullException("remote_end");
  714. }
  715. Connect_internal(socket, remote_end.Serialize());
  716. connected=true;
  717. }
  718. public Socket EndAccept(IAsyncResult result) {
  719. if (disposed && closed)
  720. throw new ObjectDisposedException (GetType ().ToString ());
  721. if (result == null)
  722. throw new ArgumentNullException ("result");
  723. SocketAsyncResult req = result as SocketAsyncResult;
  724. if (req == null)
  725. throw new ArgumentException ("Invalid IAsyncResult");
  726. result.AsyncWaitHandle.WaitOne();
  727. Interlocked.Decrement (ref pendingEnds);
  728. CheckIfClose ();
  729. req.CheckIfThrowDelayedException();
  730. return(req.Worker.Socket);
  731. }
  732. public void EndConnect(IAsyncResult result) {
  733. if (disposed && closed)
  734. throw new ObjectDisposedException (GetType ().ToString ());
  735. if (result == null)
  736. throw new ArgumentNullException ("result");
  737. SocketAsyncResult req = result as SocketAsyncResult;
  738. if (req == null)
  739. throw new ArgumentException ("Invalid IAsyncResult");
  740. result.AsyncWaitHandle.WaitOne();
  741. Interlocked.Decrement (ref pendingEnds);
  742. CheckIfClose ();
  743. req.CheckIfThrowDelayedException();
  744. }
  745. public int EndReceive(IAsyncResult result) {
  746. if (disposed && closed)
  747. throw new ObjectDisposedException (GetType ().ToString ());
  748. if (result == null)
  749. throw new ArgumentNullException ("result");
  750. SocketAsyncResult req = result as SocketAsyncResult;
  751. if (req == null)
  752. throw new ArgumentException ("Invalid IAsyncResult");
  753. result.AsyncWaitHandle.WaitOne();
  754. Interlocked.Decrement (ref pendingEnds);
  755. CheckIfClose ();
  756. req.CheckIfThrowDelayedException();
  757. return(req.Worker.Total);
  758. }
  759. public int EndReceiveFrom(IAsyncResult result,
  760. ref EndPoint end_point) {
  761. if (disposed && closed)
  762. throw new ObjectDisposedException (GetType ().ToString ());
  763. if (result == null)
  764. throw new ArgumentNullException ("result");
  765. SocketAsyncResult req = result as SocketAsyncResult;
  766. if (req == null)
  767. throw new ArgumentException ("Invalid IAsyncResult");
  768. result.AsyncWaitHandle.WaitOne();
  769. Interlocked.Decrement (ref pendingEnds);
  770. CheckIfClose ();
  771. req.CheckIfThrowDelayedException();
  772. end_point=req.Worker.EndPoint;
  773. return(req.Worker.Total);
  774. }
  775. public int EndSend(IAsyncResult result) {
  776. if (disposed && closed)
  777. throw new ObjectDisposedException (GetType ().ToString ());
  778. if (result == null)
  779. throw new ArgumentNullException ("result");
  780. SocketAsyncResult req = result as SocketAsyncResult;
  781. if (req == null)
  782. throw new ArgumentException ("Invalid IAsyncResult");
  783. result.AsyncWaitHandle.WaitOne();
  784. Interlocked.Decrement (ref pendingEnds);
  785. CheckIfClose ();
  786. req.CheckIfThrowDelayedException();
  787. return(req.Worker.Total);
  788. }
  789. public int EndSendTo(IAsyncResult result) {
  790. if (disposed && closed)
  791. throw new ObjectDisposedException (GetType ().ToString ());
  792. if (result == null)
  793. throw new ArgumentNullException ("result");
  794. SocketAsyncResult req = result as SocketAsyncResult;
  795. if (req == null)
  796. throw new ArgumentException ("Invalid IAsyncResult");
  797. result.AsyncWaitHandle.WaitOne();
  798. Interlocked.Decrement (ref pendingEnds);
  799. CheckIfClose ();
  800. req.CheckIfThrowDelayedException();
  801. return(req.Worker.Total);
  802. }
  803. void CheckIfClose ()
  804. {
  805. if (Interlocked.CompareExchange (ref closeDelayed, 1, 0) == 1) {
  806. closed = true;
  807. Close_internal(socket);
  808. }
  809. }
  810. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  811. private extern static void GetSocketOption_obj_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, out object obj_val);
  812. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  813. private extern static void GetSocketOption_arr_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val);
  814. public object GetSocketOption(SocketOptionLevel level,
  815. SocketOptionName name) {
  816. object obj_val;
  817. GetSocketOption_obj_internal(socket, level, name,
  818. out obj_val);
  819. if(name==SocketOptionName.Linger) {
  820. return((LingerOption)obj_val);
  821. } else if (name==SocketOptionName.AddMembership ||
  822. name==SocketOptionName.DropMembership) {
  823. return((MulticastOption)obj_val);
  824. } else {
  825. return((int)obj_val);
  826. }
  827. }
  828. public void GetSocketOption(SocketOptionLevel level,
  829. SocketOptionName name,
  830. byte[] opt_value) {
  831. int opt_value_len=opt_value.Length;
  832. GetSocketOption_arr_internal(socket, level, name,
  833. ref opt_value);
  834. }
  835. public byte[] GetSocketOption(SocketOptionLevel level,
  836. SocketOptionName name,
  837. int length) {
  838. byte[] byte_val=new byte[length];
  839. GetSocketOption_arr_internal(socket, level, name,
  840. ref byte_val);
  841. return(byte_val);
  842. }
  843. [MonoTODO("Totally undocumented")]
  844. public int IOControl(int ioctl_code, byte[] in_value,
  845. byte[] out_value) {
  846. throw new NotImplementedException();
  847. }
  848. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  849. private extern static void Listen_internal(IntPtr sock,
  850. int backlog);
  851. public void Listen(int backlog) {
  852. Listen_internal(socket, backlog);
  853. }
  854. /* The docs for Poll() are a bit lightweight too, but
  855. * it seems to be just a simple wrapper around Select.
  856. */
  857. public bool Poll(int time_us, SelectMode mode) {
  858. Socket [] socketlist = new Socket []{this};
  859. Socket [] n = null;
  860. switch(mode) {
  861. case SelectMode.SelectError:
  862. Select_internal (ref n, ref n, ref socketlist, time_us);
  863. break;
  864. case SelectMode.SelectRead:
  865. Select_internal (ref socketlist, ref n, ref n, time_us);
  866. break;
  867. case SelectMode.SelectWrite:
  868. Select_internal (ref n, ref socketlist, ref n, time_us);
  869. break;
  870. default:
  871. throw new NotSupportedException();
  872. }
  873. return (socketlist.Length == 1);
  874. }
  875. public int Receive(byte[] buf) {
  876. return(Receive(buf, 0, buf.Length, SocketFlags.None));
  877. }
  878. public int Receive(byte[] buf, SocketFlags flags) {
  879. return(Receive(buf, 0, buf.Length, flags));
  880. }
  881. public int Receive(byte[] buf, int size, SocketFlags flags) {
  882. return(Receive(buf, 0, size, flags));
  883. }
  884. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  885. private extern static int Receive_internal(IntPtr sock,
  886. byte[] buffer,
  887. int offset,
  888. int count,
  889. SocketFlags flags);
  890. public int Receive(byte[] buf, int offset, int size,
  891. SocketFlags flags) {
  892. if(buf==null) {
  893. throw new ArgumentNullException("buffer is null");
  894. }
  895. if(offset<0 || offset > buf.Length) {
  896. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  897. }
  898. if(size<0 || offset+size > buf.Length) {
  899. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  900. }
  901. int ret;
  902. try {
  903. ret=Receive_internal(socket, buf, offset,
  904. size, flags);
  905. } catch(SocketException) {
  906. connected=false;
  907. throw;
  908. }
  909. connected=true;
  910. return(ret);
  911. }
  912. public int ReceiveFrom(byte[] buf, ref EndPoint remote_end) {
  913. return(ReceiveFrom(buf, 0, buf.Length,
  914. SocketFlags.None, ref remote_end));
  915. }
  916. public int ReceiveFrom(byte[] buf, SocketFlags flags,
  917. ref EndPoint remote_end) {
  918. return(ReceiveFrom(buf, 0, buf.Length, flags,
  919. ref remote_end));
  920. }
  921. public int ReceiveFrom(byte[] buf, int size, SocketFlags flags,
  922. ref EndPoint remote_end) {
  923. return(ReceiveFrom(buf, 0, size, flags,
  924. ref remote_end));
  925. }
  926. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  927. private extern static int RecvFrom_internal(IntPtr sock,
  928. byte[] buffer,
  929. int offset,
  930. int count,
  931. SocketFlags flags,
  932. ref SocketAddress sockaddr);
  933. public int ReceiveFrom(byte[] buf, int offset, int size,
  934. SocketFlags flags,
  935. ref EndPoint remote_end) {
  936. if(buf==null) {
  937. throw new ArgumentNullException("buffer is null");
  938. }
  939. if(remote_end==null) {
  940. throw new ArgumentNullException("remote endpoint is null");
  941. }
  942. if(offset<0 || offset>buf.Length) {
  943. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  944. }
  945. if(size<0 || offset+size>buf.Length) {
  946. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  947. }
  948. SocketAddress sockaddr=remote_end.Serialize();
  949. int count;
  950. try {
  951. count=RecvFrom_internal(socket, buf, offset,
  952. size, flags,
  953. ref sockaddr);
  954. } catch(SocketException) {
  955. connected=false;
  956. throw;
  957. }
  958. connected=true;
  959. // Stupidly, EndPoint.Create() is an
  960. // instance method
  961. remote_end=remote_end.Create(sockaddr);
  962. return(count);
  963. }
  964. public int Send(byte[] buf) {
  965. return(Send(buf, 0, buf.Length, SocketFlags.None));
  966. }
  967. public int Send(byte[] buf, SocketFlags flags) {
  968. return(Send(buf, 0, buf.Length, flags));
  969. }
  970. public int Send(byte[] buf, int size, SocketFlags flags) {
  971. return(Send(buf, 0, size, flags));
  972. }
  973. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  974. private extern static int Send_internal(IntPtr sock,
  975. byte[] buf, int offset,
  976. int count,
  977. SocketFlags flags);
  978. public int Send (byte[] buf, int offset, int size, SocketFlags flags)
  979. {
  980. if (buf == null)
  981. throw new ArgumentNullException ("buffer");
  982. if (offset < 0 || offset > buf.Length)
  983. throw new ArgumentOutOfRangeException ("offset");
  984. if (size < 0 || offset + size > buf.Length)
  985. throw new ArgumentOutOfRangeException ("size");
  986. if (size == 0)
  987. return 0;
  988. int ret;
  989. try {
  990. ret = Send_internal (socket, buf, offset, size, flags);
  991. } catch (SocketException) {
  992. connected = false;
  993. throw;
  994. }
  995. connected = true;
  996. return ret;
  997. }
  998. public int SendTo(byte[] buffer, EndPoint remote_end) {
  999. return(SendTo(buffer, 0, buffer.Length,
  1000. SocketFlags.None, remote_end));
  1001. }
  1002. public int SendTo(byte[] buffer, SocketFlags flags,
  1003. EndPoint remote_end) {
  1004. return(SendTo(buffer, 0, buffer.Length, flags,
  1005. remote_end));
  1006. }
  1007. public int SendTo(byte[] buffer, int size, SocketFlags flags,
  1008. EndPoint remote_end) {
  1009. return(SendTo(buffer, 0, size, flags, remote_end));
  1010. }
  1011. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1012. private extern static int SendTo_internal(IntPtr sock,
  1013. byte[] buffer,
  1014. int offset,
  1015. int count,
  1016. SocketFlags flags,
  1017. SocketAddress sa);
  1018. public int SendTo(byte[] buffer, int offset, int size,
  1019. SocketFlags flags, EndPoint remote_end) {
  1020. if(buffer==null) {
  1021. throw new ArgumentNullException("buffer is null");
  1022. }
  1023. if(remote_end==null) {
  1024. throw new ArgumentNullException("remote endpoint is null");
  1025. }
  1026. if(offset<0 || offset>buffer.Length) {
  1027. throw new ArgumentOutOfRangeException("offset exceeds the size of buffer");
  1028. }
  1029. if(size<0 || offset+size>buffer.Length) {
  1030. throw new ArgumentOutOfRangeException("offset+size exceeds the size of buffer");
  1031. }
  1032. SocketAddress sockaddr=remote_end.Serialize();
  1033. int ret;
  1034. try {
  1035. ret=SendTo_internal(socket, buffer, offset,
  1036. size, flags, sockaddr);
  1037. }
  1038. catch(SocketException) {
  1039. connected=false;
  1040. throw;
  1041. }
  1042. connected=true;
  1043. return(ret);
  1044. }
  1045. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1046. private extern static void SetSocketOption_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, object obj_val, byte[] byte_val, int int_val);
  1047. public void SetSocketOption(SocketOptionLevel level,
  1048. SocketOptionName name,
  1049. byte[] opt_value) {
  1050. SetSocketOption_internal(socket, level, name, null,
  1051. opt_value, 0);
  1052. }
  1053. public void SetSocketOption(SocketOptionLevel level,
  1054. SocketOptionName name,
  1055. int opt_value) {
  1056. SetSocketOption_internal(socket, level, name, null,
  1057. null, opt_value);
  1058. }
  1059. public void SetSocketOption(SocketOptionLevel level,
  1060. SocketOptionName name,
  1061. object opt_value) {
  1062. if(opt_value==null) {
  1063. throw new ArgumentNullException();
  1064. }
  1065. /* Passing a bool as the third parameter to
  1066. * SetSocketOption causes this overload to be
  1067. * used when in fact we want to pass the value
  1068. * to the runtime as an int.
  1069. */
  1070. if(opt_value is System.Boolean) {
  1071. bool bool_val=(bool)opt_value;
  1072. /* Stupid casting rules :-( */
  1073. if(bool_val==true) {
  1074. SetSocketOption_internal(socket, level,
  1075. name, null,
  1076. null, 1);
  1077. } else {
  1078. SetSocketOption_internal(socket, level,
  1079. name, null,
  1080. null, 0);
  1081. }
  1082. } else {
  1083. SetSocketOption_internal(socket, level, name,
  1084. opt_value, null, 0);
  1085. }
  1086. }
  1087. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1088. private extern static void Shutdown_internal(IntPtr socket, SocketShutdown how);
  1089. public void Shutdown(SocketShutdown how) {
  1090. Shutdown_internal(socket, how);
  1091. }
  1092. public override int GetHashCode ()
  1093. {
  1094. return (int) socket;
  1095. }
  1096. private bool disposed;
  1097. protected virtual void Dispose(bool explicitDisposing) {
  1098. // Check to see if Dispose has already been called
  1099. if(!this.disposed) {
  1100. // If this is a call to Dispose,
  1101. // dispose all managed resources.
  1102. if(explicitDisposing) {
  1103. // Free up stuff here
  1104. }
  1105. // Release unmanaged resources
  1106. this.disposed=true;
  1107. connected=false;
  1108. Interlocked.CompareExchange (ref closeDelayed, 0, 1);
  1109. if (Interlocked.CompareExchange (ref pendingEnds, 0, 0) == 0) {
  1110. if (Interlocked.CompareExchange (ref closeDelayed, 1, 0) == 1) {
  1111. closed = true;
  1112. Close_internal(socket);
  1113. }
  1114. }
  1115. }
  1116. }
  1117. void IDisposable.Dispose ()
  1118. {
  1119. Dispose (true);
  1120. GC.SuppressFinalize (this);
  1121. }
  1122. ~Socket () {
  1123. Dispose(false);
  1124. }
  1125. }
  1126. }