Socket.cs 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  1. // System.Net.Sockets.Socket.cs
  2. //
  3. // Authors:
  4. // Phillip Pearson ([email protected])
  5. // Dick Porter <[email protected]>
  6. // Gonzalo Paniagua Javier ([email protected])
  7. //
  8. // Copyright (C) 2001, 2002 Phillip Pearson and Ximian, Inc.
  9. // http://www.myelin.co.nz
  10. // (c) 2004 Novell, Inc. (http://www.novell.com)
  11. //
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System;
  33. using System.Net;
  34. using System.Collections;
  35. using System.Runtime.CompilerServices;
  36. using System.Runtime.InteropServices;
  37. using System.Threading;
  38. using System.Reflection;
  39. using System.IO;
  40. namespace System.Net.Sockets
  41. {
  42. public class Socket : IDisposable
  43. {
  44. [StructLayout (LayoutKind.Sequential)]
  45. private sealed class SocketAsyncResult: IAsyncResult
  46. {
  47. /* Same structure in the runtime */
  48. public Socket Sock;
  49. IntPtr handle;
  50. object state;
  51. AsyncCallback callback;
  52. WaitHandle waithandle;
  53. Exception delayedException;
  54. public EndPoint EndPoint; // Connect,ReceiveFrom,SendTo
  55. public byte [] Buffer; // Receive,ReceiveFrom,Send,SendTo
  56. public int Offset; // Receive,ReceiveFrom,Send,SendTo
  57. public int Size; // Receive,ReceiveFrom,Send,SendTo
  58. public SocketFlags SockFlags; // Receive,ReceiveFrom,Send,SendTo
  59. // Return values
  60. Socket acc_socket;
  61. int total;
  62. bool completed_sync;
  63. bool completed;
  64. AsyncCallback real_callback;
  65. int error;
  66. public SocketAsyncResult (Socket sock, object state, AsyncCallback callback)
  67. {
  68. this.Sock = sock;
  69. this.handle = sock.socket;
  70. this.state = state;
  71. this.real_callback = callback;
  72. SockFlags = SocketFlags.None;
  73. }
  74. public void CreateAsyncDelegate ()
  75. {
  76. if (real_callback != null)
  77. this.callback = new AsyncCallback (FakeCB);
  78. }
  79. static void FakeCB (IAsyncResult result)
  80. {
  81. SocketAsyncResult ares = (SocketAsyncResult) result;
  82. ares.real_callback.BeginInvoke (ares, null, null);
  83. }
  84. public void CheckIfThrowDelayedException ()
  85. {
  86. if (delayedException != null)
  87. throw delayedException;
  88. if (error != 0)
  89. throw new SocketException (error);
  90. }
  91. public void Complete ()
  92. {
  93. IsCompleted = true;
  94. if (real_callback != null)
  95. real_callback (this);
  96. }
  97. public void Complete (int total)
  98. {
  99. this.total = total;
  100. Complete ();
  101. }
  102. public void Complete (Exception e)
  103. {
  104. delayedException = e;
  105. Complete ();
  106. }
  107. public void Complete (Socket s)
  108. {
  109. acc_socket = s;
  110. Complete ();
  111. }
  112. public object AsyncState {
  113. get {
  114. return state;
  115. }
  116. }
  117. public WaitHandle AsyncWaitHandle {
  118. get {
  119. lock (this) {
  120. if (waithandle == null)
  121. waithandle = new ManualResetEvent (completed);
  122. }
  123. return waithandle;
  124. }
  125. set {
  126. waithandle=value;
  127. }
  128. }
  129. public bool CompletedSynchronously {
  130. get {
  131. return(completed_sync);
  132. }
  133. }
  134. public bool IsCompleted {
  135. get {
  136. return(completed);
  137. }
  138. set {
  139. completed=value;
  140. lock (this) {
  141. if (waithandle != null && value) {
  142. ((ManualResetEvent) waithandle).Set ();
  143. }
  144. }
  145. }
  146. }
  147. public Socket Socket {
  148. get {
  149. return acc_socket;
  150. }
  151. }
  152. public int Total {
  153. get {
  154. return total;
  155. }
  156. }
  157. }
  158. private sealed class Worker
  159. {
  160. SocketAsyncResult result;
  161. public Worker (SocketAsyncResult ares)
  162. {
  163. this.result = ares;
  164. }
  165. public void Accept ()
  166. {
  167. lock (result) {
  168. Socket acc_socket = null;
  169. try {
  170. if (!result.Sock.blocking)
  171. result.Sock.Poll (-1, SelectMode.SelectRead);
  172. acc_socket = result.Sock.Accept ();
  173. } catch (Exception e) {
  174. result.Complete (e);
  175. return;
  176. }
  177. result.Complete (acc_socket);
  178. }
  179. }
  180. public void Connect ()
  181. {
  182. lock (result) {
  183. try {
  184. result.Sock.Connect (result.EndPoint);
  185. } catch (SocketException se) {
  186. if (result.Sock.blocking || se.ErrorCode != 10036) {
  187. result.Complete (se);
  188. return;
  189. }
  190. try {
  191. result.Sock.Poll (-1, SelectMode.SelectWrite);
  192. result.Sock.Connect (result.EndPoint);
  193. } catch (Exception k) {
  194. result.Complete (k);
  195. return;
  196. }
  197. } catch (Exception e) {
  198. result.Complete (e);
  199. return;
  200. }
  201. result.Complete ();
  202. }
  203. }
  204. public void Receive ()
  205. {
  206. lock (result) {
  207. int total = 0;
  208. try {
  209. if (!result.Sock.blocking)
  210. result.Sock.Poll (-1, SelectMode.SelectRead);
  211. total = result.Sock.Receive_nochecks (result.Buffer,
  212. result.Offset,
  213. result.Size,
  214. result.SockFlags);
  215. } catch (Exception e) {
  216. result.Complete (e);
  217. return;
  218. }
  219. result.Complete (total);
  220. }
  221. }
  222. public void ReceiveFrom ()
  223. {
  224. lock (result) {
  225. int total = 0;
  226. try {
  227. if (!result.Sock.blocking)
  228. result.Sock.Poll (-1, SelectMode.SelectRead);
  229. total = result.Sock.ReceiveFrom_nochecks (result.Buffer,
  230. result.Offset,
  231. result.Size,
  232. result.SockFlags,
  233. ref result.EndPoint);
  234. } catch (Exception e) {
  235. result.Complete (e);
  236. return;
  237. }
  238. result.Complete (total);
  239. }
  240. }
  241. public void Send ()
  242. {
  243. lock (result) {
  244. int total = 0;
  245. try {
  246. if (!result.Sock.blocking)
  247. result.Sock.Poll (-1, SelectMode.SelectWrite);
  248. total = result.Sock.Send_nochecks (result.Buffer,
  249. result.Offset,
  250. result.Size,
  251. result.SockFlags);
  252. } catch (Exception e) {
  253. result.Complete (e);
  254. return;
  255. }
  256. result.Complete (total);
  257. }
  258. }
  259. public void SendTo() {
  260. lock (result) {
  261. int total = 0;
  262. try {
  263. if (!result.Sock.blocking)
  264. result.Sock.Poll (-1, SelectMode.SelectWrite);
  265. total = result.Sock.SendTo_nochecks (result.Buffer,
  266. result.Offset,
  267. result.Size,
  268. result.SockFlags,
  269. result.EndPoint);
  270. } catch (Exception e) {
  271. result.Complete (e);
  272. return;
  273. }
  274. result.Complete (total);
  275. }
  276. }
  277. }
  278. /* the field "socket" is looked up by name by the runtime */
  279. private IntPtr socket;
  280. private AddressFamily address_family;
  281. private SocketType socket_type;
  282. private ProtocolType protocol_type;
  283. internal bool blocking=true;
  284. private int pendingEnds;
  285. private int closeDelayed;
  286. static readonly bool supportsAsync = FakeGetSupportsAsync ();
  287. delegate void SocketAsyncCall ();
  288. /*
  289. * These two fields are looked up by name by the runtime, don't change
  290. * their name without also updating the runtime code.
  291. */
  292. private static int ipv4Supported = -1, ipv6Supported = -1;
  293. /* When true, the socket was connected at the time of
  294. * the last IO operation
  295. */
  296. private bool connected=false;
  297. /* true if we called Close_internal */
  298. private bool closed;
  299. /* Used in LocalEndPoint and RemoteEndPoint if the
  300. * Mono.Posix assembly is available
  301. */
  302. private static object unixendpoint=null;
  303. private static Type unixendpointtype=null;
  304. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  305. private extern static void Select_internal(ref Socket[] read,
  306. ref Socket[] write,
  307. ref Socket[] err,
  308. int timeout,
  309. out int error);
  310. public static void Select(IList read_list, IList write_list,
  311. IList err_list, int time_us) {
  312. int read_count = 0, write_count = 0, err_count = 0;
  313. Socket[] read_arr = null;
  314. Socket[] write_arr = null;
  315. Socket[] err_arr = null;
  316. if (read_list!=null)
  317. read_count=read_list.Count;
  318. if (read_count != 0)
  319. read_arr=new Socket[read_count];
  320. if (write_list!=null)
  321. write_count=write_list.Count;
  322. if (write_count != 0)
  323. write_arr=new Socket[write_count];
  324. if (err_list!=null)
  325. err_count=err_list.Count;
  326. if (err_count != 0)
  327. err_arr=new Socket[err_count];
  328. if(read_count == 0 && write_count == 0 && err_count == 0) {
  329. throw new ArgumentNullException ("read_list, write_list, err_list",
  330. "All the lists are null or empty.");
  331. }
  332. int i;
  333. if (read_count != 0) {
  334. i=0;
  335. foreach (Socket s in read_list) {
  336. read_arr[i]=s;
  337. i++;
  338. }
  339. }
  340. if (write_count != 0) {
  341. i=0;
  342. foreach (Socket s in write_list) {
  343. write_arr[i]=s;
  344. i++;
  345. }
  346. }
  347. if (err_count != 0) {
  348. i=0;
  349. foreach (Socket s in err_list) {
  350. err_arr[i]=s;
  351. i++;
  352. }
  353. }
  354. int error;
  355. Select_internal(ref read_arr, ref write_arr,
  356. ref err_arr, time_us, out error);
  357. if(error != 0) {
  358. throw new SocketException (error);
  359. }
  360. /* Make sure the connected state is updated
  361. * for each socket returned from the select;
  362. * for non blocking Connect()s, this is when
  363. * we find out that the connect succeeded.
  364. */
  365. if(read_list!=null) {
  366. read_list.Clear();
  367. if (read_arr != null) {
  368. for(i=0; i<read_arr.Length; i++) {
  369. read_list.Add(read_arr[i]);
  370. read_arr[i].connected = true;
  371. }
  372. }
  373. }
  374. if(write_list!=null) {
  375. write_list.Clear();
  376. if (write_arr != null) {
  377. for(i=0; i<write_arr.Length; i++) {
  378. write_list.Add(write_arr[i]);
  379. write_arr[i].connected = true;
  380. }
  381. }
  382. }
  383. if(err_list!=null) {
  384. err_list.Clear();
  385. if (err_arr != null) {
  386. for(i=0; i<err_arr.Length; i++) {
  387. err_list.Add(err_arr[i]);
  388. err_arr[i].connected = true;
  389. }
  390. }
  391. }
  392. }
  393. static Socket() {
  394. Assembly ass;
  395. try {
  396. ass = Assembly.Load (Consts.AssemblyMono_Posix);
  397. } catch (FileNotFoundException) {
  398. return;
  399. }
  400. unixendpointtype=ass.GetType("Mono.Posix.UnixEndPoint");
  401. /* The endpoint Create() method is an instance
  402. * method :-(
  403. */
  404. Type[] arg_types=new Type[1];
  405. arg_types[0]=typeof(string);
  406. ConstructorInfo cons=unixendpointtype.GetConstructor(arg_types);
  407. object[] args=new object[1];
  408. args[0]="";
  409. unixendpoint=cons.Invoke(args);
  410. }
  411. // private constructor used by Accept, which already
  412. // has a socket handle to use
  413. private Socket(AddressFamily family, SocketType type,
  414. ProtocolType proto, IntPtr sock) {
  415. address_family=family;
  416. socket_type=type;
  417. protocol_type=proto;
  418. socket=sock;
  419. connected=true;
  420. }
  421. // Creates a new system socket, returning the handle
  422. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  423. private extern IntPtr Socket_internal(AddressFamily family,
  424. SocketType type,
  425. ProtocolType proto,
  426. out int error);
  427. public Socket(AddressFamily family, SocketType type,
  428. ProtocolType proto) {
  429. address_family=family;
  430. socket_type=type;
  431. protocol_type=proto;
  432. int error;
  433. socket=Socket_internal(family, type, proto, out error);
  434. if (error != 0) {
  435. throw new SocketException (error);
  436. }
  437. }
  438. public AddressFamily AddressFamily {
  439. get {
  440. return(address_family);
  441. }
  442. }
  443. // Returns the amount of data waiting to be read on socket
  444. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  445. private extern static int Available_internal(IntPtr socket,
  446. out int error);
  447. public int Available {
  448. get {
  449. if (disposed && closed)
  450. throw new ObjectDisposedException (GetType ().ToString ());
  451. int ret, error;
  452. ret = Available_internal(socket, out error);
  453. if (error != 0) {
  454. throw new SocketException (error);
  455. }
  456. return(ret);
  457. }
  458. }
  459. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  460. private extern static void Blocking_internal(IntPtr socket,
  461. bool block,
  462. out int error);
  463. public bool Blocking {
  464. get {
  465. return(blocking);
  466. }
  467. set {
  468. int error;
  469. Blocking_internal(socket, value, out error);
  470. if (error != 0) {
  471. throw new SocketException (error);
  472. }
  473. blocking=value;
  474. }
  475. }
  476. public bool Connected {
  477. get {
  478. return(connected);
  479. }
  480. }
  481. public IntPtr Handle {
  482. get {
  483. return(socket);
  484. }
  485. }
  486. // Returns the local endpoint details in addr and port
  487. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  488. private extern static SocketAddress LocalEndPoint_internal(IntPtr socket, out int error);
  489. [MonoTODO("Support non-IP endpoints")]
  490. public EndPoint LocalEndPoint {
  491. get {
  492. if (disposed && closed)
  493. throw new ObjectDisposedException (GetType ().ToString ());
  494. SocketAddress sa;
  495. int error;
  496. sa=LocalEndPoint_internal(socket, out error);
  497. if (error != 0) {
  498. throw new SocketException (error);
  499. }
  500. if(sa.Family==AddressFamily.InterNetwork || sa.Family==AddressFamily.InterNetworkV6) {
  501. // Stupidly, EndPoint.Create() is an
  502. // instance method
  503. return new IPEndPoint(0, 0).Create(sa);
  504. } else if (sa.Family==AddressFamily.Unix &&
  505. unixendpoint!=null) {
  506. return((EndPoint)unixendpointtype.InvokeMember("Create", BindingFlags.InvokeMethod|BindingFlags.Instance|BindingFlags.Public, null, unixendpoint, new object[] {sa}));
  507. } else {
  508. throw new NotImplementedException();
  509. }
  510. }
  511. }
  512. public ProtocolType ProtocolType {
  513. get {
  514. return(protocol_type);
  515. }
  516. }
  517. // Returns the remote endpoint details in addr and port
  518. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  519. private extern static SocketAddress RemoteEndPoint_internal(IntPtr socket, out int error);
  520. [MonoTODO("Support non-IP endpoints")]
  521. public EndPoint RemoteEndPoint {
  522. get {
  523. if (disposed && closed)
  524. throw new ObjectDisposedException (GetType ().ToString ());
  525. SocketAddress sa;
  526. int error;
  527. sa=RemoteEndPoint_internal(socket, out error);
  528. if (error != 0) {
  529. throw new SocketException (error);
  530. }
  531. if(sa.Family==AddressFamily.InterNetwork || sa.Family==AddressFamily.InterNetworkV6 ) {
  532. // Stupidly, EndPoint.Create() is an
  533. // instance method
  534. return new IPEndPoint(0, 0).Create(sa);
  535. } else if (sa.Family==AddressFamily.Unix &&
  536. unixendpoint!=null) {
  537. return((EndPoint)unixendpointtype.InvokeMember("Create", BindingFlags.InvokeMethod|BindingFlags.Instance|BindingFlags.Public, null, unixendpoint, new object[] {sa}));
  538. } else {
  539. throw new NotImplementedException();
  540. }
  541. }
  542. }
  543. public SocketType SocketType {
  544. get {
  545. return(socket_type);
  546. }
  547. }
  548. #if NET_1_1
  549. public static bool SupportsIPv4 {
  550. get {
  551. CheckProtocolSupport();
  552. return ipv4Supported == 1;
  553. }
  554. }
  555. public static bool SupportsIPv6 {
  556. get {
  557. CheckProtocolSupport();
  558. return ipv6Supported == 1;
  559. }
  560. }
  561. #else
  562. internal static bool SupportsIPv4
  563. {
  564. get
  565. {
  566. return true;
  567. }
  568. }
  569. internal static bool SupportsIPv6
  570. {
  571. get
  572. {
  573. return false;
  574. }
  575. }
  576. #endif
  577. internal static void CheckProtocolSupport()
  578. {
  579. if(ipv4Supported == -1) {
  580. try {
  581. Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  582. tmp.Close();
  583. ipv4Supported = 1;
  584. }
  585. catch {
  586. ipv4Supported = 0;
  587. }
  588. }
  589. if(ipv6Supported == -1) {
  590. NetConfig config = (NetConfig)System.Configuration.ConfigurationSettings.GetConfig("system.net/settings");
  591. if(config != null)
  592. ipv6Supported = config.ipv6Enabled?-1:0;
  593. if(ipv6Supported != 0) {
  594. try {
  595. Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
  596. tmp.Close();
  597. ipv6Supported = 1;
  598. }
  599. catch { }
  600. }
  601. }
  602. }
  603. // Creates a new system socket, returning the handle
  604. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  605. private extern static IntPtr Accept_internal(IntPtr sock,
  606. out int error);
  607. public Socket Accept() {
  608. if (disposed && closed)
  609. throw new ObjectDisposedException (GetType ().ToString ());
  610. int error;
  611. IntPtr sock=Accept_internal(socket, out error);
  612. if (!blocking && error == 10035) {
  613. Poll (-1, SelectMode.SelectRead);
  614. sock = Accept_internal (socket, out error);
  615. }
  616. if (error != 0) {
  617. throw new SocketException (error);
  618. }
  619. return(new Socket(this.AddressFamily, this.SocketType,
  620. this.ProtocolType, sock));
  621. }
  622. public IAsyncResult BeginAccept(AsyncCallback callback,
  623. object state) {
  624. if (disposed && closed)
  625. throw new ObjectDisposedException (GetType ().ToString ());
  626. Interlocked.Increment (ref pendingEnds);
  627. SocketAsyncResult req = new SocketAsyncResult (this, state, callback);
  628. Worker worker = new Worker (req);
  629. SocketAsyncCall sac = new SocketAsyncCall (worker.Accept);
  630. sac.BeginInvoke (null, null);
  631. return(req);
  632. }
  633. public IAsyncResult BeginConnect(EndPoint end_point,
  634. AsyncCallback callback,
  635. object state) {
  636. if (disposed && closed)
  637. throw new ObjectDisposedException (GetType ().ToString ());
  638. if (end_point == null)
  639. throw new ArgumentNullException ("end_point");
  640. Interlocked.Increment (ref pendingEnds);
  641. SocketAsyncResult req = new SocketAsyncResult (this, state, callback);
  642. req.EndPoint = end_point;
  643. Worker worker = new Worker (req);
  644. SocketAsyncCall sac = new SocketAsyncCall (worker.Connect);
  645. sac.BeginInvoke (null, null);
  646. return(req);
  647. }
  648. public IAsyncResult BeginReceive(byte[] buffer, int offset,
  649. int size,
  650. SocketFlags socket_flags,
  651. AsyncCallback callback,
  652. object state) {
  653. if (disposed && closed)
  654. throw new ObjectDisposedException (GetType ().ToString ());
  655. if (buffer == null)
  656. throw new ArgumentNullException ("buffer");
  657. if (offset < 0 || offset > buffer.Length)
  658. throw new ArgumentOutOfRangeException ("offset");
  659. if (size < 0 || offset + size > buffer.Length)
  660. throw new ArgumentOutOfRangeException ("size");
  661. Interlocked.Increment (ref pendingEnds);
  662. SocketAsyncResult req = new SocketAsyncResult (this, state, callback);
  663. req.Buffer = buffer;
  664. req.Offset = offset;
  665. req.Size = size;
  666. req.SockFlags = socket_flags;
  667. if (supportsAsync && socket_type == SocketType.Stream) {
  668. int error;
  669. req.CreateAsyncDelegate ();
  670. KeepReference (req);
  671. AsyncReceiveInternal (req, out error);
  672. if (error != 0 && error != 10036) // WSAEINPROGRESS
  673. throw new SocketException (error);
  674. } else {
  675. Worker worker = new Worker (req);
  676. SocketAsyncCall sac = new SocketAsyncCall (worker.Receive);
  677. sac.BeginInvoke (null, null);
  678. }
  679. return req;
  680. }
  681. public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset,
  682. int size,
  683. SocketFlags socket_flags,
  684. ref EndPoint remote_end,
  685. AsyncCallback callback,
  686. object state) {
  687. if (disposed && closed)
  688. throw new ObjectDisposedException (GetType ().ToString ());
  689. if (buffer == null)
  690. throw new ArgumentNullException ("buffer");
  691. if (offset < 0)
  692. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  693. if (size < 0)
  694. throw new ArgumentOutOfRangeException ("size must be >= 0");
  695. if (offset + size > buffer.Length)
  696. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  697. Interlocked.Increment (ref pendingEnds);
  698. SocketAsyncResult req = new SocketAsyncResult (this, state, callback);
  699. req.Buffer = buffer;
  700. req.Offset = offset;
  701. req.Size = size;
  702. req.SockFlags = socket_flags;
  703. req.EndPoint = remote_end;
  704. Worker worker = new Worker (req);
  705. SocketAsyncCall sac = new SocketAsyncCall (worker.ReceiveFrom);
  706. sac.BeginInvoke (null, null);
  707. return req;
  708. }
  709. public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socket_flags,
  710. AsyncCallback callback, object state)
  711. {
  712. if (disposed && closed)
  713. throw new ObjectDisposedException (GetType ().ToString ());
  714. if (buffer == null)
  715. throw new ArgumentNullException ("buffer");
  716. if (offset < 0)
  717. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  718. if (size < 0)
  719. throw new ArgumentOutOfRangeException ("size must be >= 0");
  720. if (offset + size > buffer.Length)
  721. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  722. Interlocked.Increment (ref pendingEnds);
  723. SocketAsyncResult req = new SocketAsyncResult (this, state, callback);
  724. req.Buffer = buffer;
  725. req.Offset = offset;
  726. req.Size = size;
  727. req.SockFlags = socket_flags;
  728. if (supportsAsync && socket_type == SocketType.Stream) {
  729. int error;
  730. req.CreateAsyncDelegate ();
  731. KeepReference (req);
  732. AsyncSendInternal (req, out error);
  733. if (error != 0 && error != 10036) // WSAEINPROGRESS
  734. throw new SocketException (error);
  735. } else {
  736. Worker worker = new Worker (req);
  737. SocketAsyncCall sac = new SocketAsyncCall (worker.Send);
  738. sac.BeginInvoke (null, null);
  739. }
  740. return req;
  741. }
  742. public IAsyncResult BeginSendTo(byte[] buffer, int offset,
  743. int size,
  744. SocketFlags socket_flags,
  745. EndPoint remote_end,
  746. AsyncCallback callback,
  747. object state) {
  748. if (disposed && closed)
  749. throw new ObjectDisposedException (GetType ().ToString ());
  750. if (buffer == null)
  751. throw new ArgumentNullException ("buffer");
  752. if (offset < 0)
  753. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  754. if (size < 0)
  755. throw new ArgumentOutOfRangeException ("size must be >= 0");
  756. if (offset + size > buffer.Length)
  757. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  758. Interlocked.Increment (ref pendingEnds);
  759. SocketAsyncResult req = new SocketAsyncResult (this, state, callback);
  760. req.Buffer = buffer;
  761. req.Offset = offset;
  762. req.Size = size;
  763. req.SockFlags = socket_flags;
  764. req.EndPoint = remote_end;
  765. Worker worker = new Worker(req);
  766. SocketAsyncCall sac = new SocketAsyncCall (worker.SendTo);
  767. sac.BeginInvoke (null, null);
  768. return req;
  769. }
  770. // Creates a new system socket, returning the handle
  771. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  772. private extern static void Bind_internal(IntPtr sock,
  773. SocketAddress sa,
  774. out int error);
  775. public void Bind(EndPoint local_end) {
  776. if (disposed && closed)
  777. throw new ObjectDisposedException (GetType ().ToString ());
  778. if(local_end==null) {
  779. throw new ArgumentNullException("local_end");
  780. }
  781. int error;
  782. Bind_internal(socket, local_end.Serialize(),
  783. out error);
  784. if (error != 0) {
  785. throw new SocketException (error);
  786. }
  787. }
  788. // Closes the socket
  789. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  790. private extern static void Close_internal(IntPtr socket,
  791. out int error);
  792. public void Close() {
  793. ((IDisposable) this).Dispose ();
  794. }
  795. // Connects to the remote address
  796. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  797. private extern static void Connect_internal(IntPtr sock,
  798. SocketAddress sa,
  799. out int error);
  800. public void Connect(EndPoint remote_end) {
  801. if (disposed && closed)
  802. throw new ObjectDisposedException (GetType ().ToString ());
  803. if(remote_end==null) {
  804. throw new ArgumentNullException("remote_end");
  805. }
  806. int error;
  807. SocketAddress serial = remote_end.Serialize ();
  808. Connect_internal(socket, serial, out error);
  809. if (!blocking && error == 10035) {
  810. Poll (-1, SelectMode.SelectWrite);
  811. Connect_internal (socket, serial, out error);
  812. }
  813. if (error != 0)
  814. throw new SocketException (error);
  815. connected=true;
  816. }
  817. public Socket EndAccept(IAsyncResult result) {
  818. if (disposed && closed)
  819. throw new ObjectDisposedException (GetType ().ToString ());
  820. if (result == null)
  821. throw new ArgumentNullException ("result");
  822. SocketAsyncResult req = result as SocketAsyncResult;
  823. if (req == null)
  824. throw new ArgumentException ("Invalid IAsyncResult", "result");
  825. if (!result.IsCompleted)
  826. result.AsyncWaitHandle.WaitOne();
  827. Interlocked.Decrement (ref pendingEnds);
  828. CheckIfClose ();
  829. req.CheckIfThrowDelayedException();
  830. return req.Socket;
  831. }
  832. public void EndConnect(IAsyncResult result) {
  833. if (disposed && closed)
  834. throw new ObjectDisposedException (GetType ().ToString ());
  835. if (result == null)
  836. throw new ArgumentNullException ("result");
  837. SocketAsyncResult req = result as SocketAsyncResult;
  838. if (req == null)
  839. throw new ArgumentException ("Invalid IAsyncResult", "result");
  840. if (!result.IsCompleted)
  841. result.AsyncWaitHandle.WaitOne();
  842. Interlocked.Decrement (ref pendingEnds);
  843. CheckIfClose ();
  844. req.CheckIfThrowDelayedException();
  845. }
  846. public int EndReceive(IAsyncResult result) {
  847. if (disposed && closed)
  848. throw new ObjectDisposedException (GetType ().ToString ());
  849. if (result == null)
  850. throw new ArgumentNullException ("result");
  851. SocketAsyncResult req = result as SocketAsyncResult;
  852. if (req == null)
  853. throw new ArgumentException ("Invalid IAsyncResult", "result");
  854. if (supportsAsync && socket_type == SocketType.Stream)
  855. RemoveReference (req);
  856. if (!result.IsCompleted)
  857. result.AsyncWaitHandle.WaitOne();
  858. Interlocked.Decrement (ref pendingEnds);
  859. CheckIfClose ();
  860. req.CheckIfThrowDelayedException();
  861. return req.Total;
  862. }
  863. public int EndReceiveFrom(IAsyncResult result,
  864. ref EndPoint end_point) {
  865. if (disposed && closed)
  866. throw new ObjectDisposedException (GetType ().ToString ());
  867. if (result == null)
  868. throw new ArgumentNullException ("result");
  869. SocketAsyncResult req = result as SocketAsyncResult;
  870. if (req == null)
  871. throw new ArgumentException ("Invalid IAsyncResult", "result");
  872. if (!result.IsCompleted)
  873. result.AsyncWaitHandle.WaitOne();
  874. Interlocked.Decrement (ref pendingEnds);
  875. CheckIfClose ();
  876. req.CheckIfThrowDelayedException();
  877. end_point = req.EndPoint;
  878. return req.Total;
  879. }
  880. public int EndSend(IAsyncResult result) {
  881. if (disposed && closed)
  882. throw new ObjectDisposedException (GetType ().ToString ());
  883. if (result == null)
  884. throw new ArgumentNullException ("result");
  885. SocketAsyncResult req = result as SocketAsyncResult;
  886. if (req == null)
  887. throw new ArgumentException ("Invalid IAsyncResult", "result");
  888. if (supportsAsync && socket_type == SocketType.Stream)
  889. RemoveReference (req);
  890. if (!result.IsCompleted)
  891. result.AsyncWaitHandle.WaitOne();
  892. Interlocked.Decrement (ref pendingEnds);
  893. CheckIfClose ();
  894. req.CheckIfThrowDelayedException();
  895. return req.Total;
  896. }
  897. public int EndSendTo(IAsyncResult result) {
  898. if (disposed && closed)
  899. throw new ObjectDisposedException (GetType ().ToString ());
  900. if (result == null)
  901. throw new ArgumentNullException ("result");
  902. SocketAsyncResult req = result as SocketAsyncResult;
  903. if (req == null)
  904. throw new ArgumentException ("Invalid IAsyncResult", "result");
  905. if (!result.IsCompleted)
  906. result.AsyncWaitHandle.WaitOne();
  907. Interlocked.Decrement (ref pendingEnds);
  908. CheckIfClose ();
  909. req.CheckIfThrowDelayedException();
  910. return req.Total;
  911. }
  912. void CheckIfClose ()
  913. {
  914. if (Interlocked.CompareExchange (ref closeDelayed, 0, 1) == 1 &&
  915. Interlocked.CompareExchange (ref pendingEnds, 0, 0) == 0) {
  916. closed = true;
  917. int error;
  918. Close_internal(socket, out error);
  919. if (error != 0) {
  920. throw new SocketException (error);
  921. }
  922. }
  923. }
  924. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  925. private extern static void GetSocketOption_obj_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error);
  926. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  927. private extern static void GetSocketOption_arr_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error);
  928. public object GetSocketOption(SocketOptionLevel level,
  929. SocketOptionName name) {
  930. object obj_val;
  931. int error;
  932. GetSocketOption_obj_internal(socket, level, name,
  933. out obj_val, out error);
  934. if (error != 0) {
  935. throw new SocketException (error);
  936. }
  937. if(name==SocketOptionName.Linger) {
  938. return((LingerOption)obj_val);
  939. } else if (name==SocketOptionName.AddMembership ||
  940. name==SocketOptionName.DropMembership) {
  941. return((MulticastOption)obj_val);
  942. } else if (obj_val is int) {
  943. return((int)obj_val);
  944. } else {
  945. return(obj_val);
  946. }
  947. }
  948. public void GetSocketOption(SocketOptionLevel level,
  949. SocketOptionName name,
  950. byte[] opt_value) {
  951. int opt_value_len=opt_value.Length;
  952. int error;
  953. GetSocketOption_arr_internal(socket, level, name,
  954. ref opt_value, out error);
  955. if (error != 0) {
  956. throw new SocketException (error);
  957. }
  958. }
  959. public byte[] GetSocketOption(SocketOptionLevel level,
  960. SocketOptionName name,
  961. int length) {
  962. byte[] byte_val=new byte[length];
  963. int error;
  964. GetSocketOption_arr_internal(socket, level, name,
  965. ref byte_val, out error);
  966. if (error != 0) {
  967. throw new SocketException (error);
  968. }
  969. return(byte_val);
  970. }
  971. // See Socket.IOControl, WSAIoctl documentation in MSDN. The
  972. // common options between UNIX and Winsock are FIONREAD,
  973. // FIONBIO and SIOCATMARK. Anything else will depend on the
  974. // system.
  975. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  976. extern static int WSAIoctl (IntPtr sock, int ioctl_code,
  977. byte [] input, byte [] output,
  978. out int error);
  979. public int IOControl (int ioctl_code, byte [] in_value, byte [] out_value)
  980. {
  981. if (disposed)
  982. throw new ObjectDisposedException (GetType ().ToString ());
  983. int error;
  984. int result = WSAIoctl (socket, ioctl_code, in_value,
  985. out_value, out error);
  986. if (error != 0) {
  987. throw new SocketException (error);
  988. }
  989. if (result == -1)
  990. throw new InvalidOperationException ("Must use Blocking property instead.");
  991. return result;
  992. }
  993. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  994. private extern static void Listen_internal(IntPtr sock,
  995. int backlog,
  996. out int error);
  997. public void Listen(int backlog) {
  998. int error;
  999. Listen_internal(socket, backlog, out error);
  1000. if (error != 0) {
  1001. throw new SocketException (error);
  1002. }
  1003. }
  1004. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1005. extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
  1006. public bool Poll (int time_us, SelectMode mode)
  1007. {
  1008. if (mode != SelectMode.SelectRead &&
  1009. mode != SelectMode.SelectWrite &&
  1010. mode != SelectMode.SelectError)
  1011. throw new NotSupportedException ("'mode' parameter is not valid.");
  1012. int error;
  1013. bool result = Poll_internal (socket, mode, time_us, out error);
  1014. if (error != 0)
  1015. throw new SocketException (error);
  1016. if (result == true) {
  1017. /* Update the connected state; for
  1018. * non-blocking Connect()s this is
  1019. * when we can find out that the
  1020. * connect succeeded.
  1021. */
  1022. connected = true;
  1023. }
  1024. return result;
  1025. }
  1026. public int Receive (byte [] buf)
  1027. {
  1028. if (buf == null)
  1029. throw new ArgumentNullException ("buf");
  1030. return Receive_nochecks (buf, 0, buf.Length, SocketFlags.None);
  1031. }
  1032. public int Receive (byte [] buf, SocketFlags flags)
  1033. {
  1034. if (buf == null)
  1035. throw new ArgumentNullException ("buf");
  1036. return Receive_nochecks (buf, 0, buf.Length, flags);
  1037. }
  1038. public int Receive (byte [] buf, int size, SocketFlags flags)
  1039. {
  1040. if (buf == null)
  1041. throw new ArgumentNullException ("buf");
  1042. if (size < 0 || size > buf.Length)
  1043. throw new ArgumentOutOfRangeException ("size");
  1044. return Receive_nochecks (buf, 0, size, flags);
  1045. }
  1046. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1047. private extern static int Receive_internal(IntPtr sock,
  1048. byte[] buffer,
  1049. int offset,
  1050. int count,
  1051. SocketFlags flags,
  1052. out int error);
  1053. public int Receive (byte [] buf, int offset, int size, SocketFlags flags)
  1054. {
  1055. if (buf == null)
  1056. throw new ArgumentNullException ("buf");
  1057. if (offset < 0 || offset > buf.Length)
  1058. throw new ArgumentOutOfRangeException ("offset");
  1059. if (size < 0 || offset + size > buf.Length)
  1060. throw new ArgumentOutOfRangeException ("size");
  1061. return Receive_nochecks (buf, offset, size, flags);
  1062. }
  1063. int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags)
  1064. {
  1065. int ret, error;
  1066. ret = Receive_internal (socket, buf, offset, size, flags, out error);
  1067. if (error != 0) {
  1068. connected = false;
  1069. throw new SocketException (error);
  1070. }
  1071. connected = true;
  1072. return ret;
  1073. }
  1074. public int ReceiveFrom (byte [] buf, ref EndPoint remote_end)
  1075. {
  1076. if (buf == null)
  1077. throw new ArgumentNullException ("buf");
  1078. if (remote_end == null)
  1079. throw new ArgumentNullException ("remote_end");
  1080. return ReceiveFrom_nochecks (buf, 0, buf.Length, SocketFlags.None, ref remote_end);
  1081. }
  1082. public int ReceiveFrom (byte [] buf, SocketFlags flags, ref EndPoint remote_end)
  1083. {
  1084. if (buf == null)
  1085. throw new ArgumentNullException ("buf");
  1086. if (remote_end == null)
  1087. throw new ArgumentNullException ("remote_end");
  1088. return ReceiveFrom_nochecks (buf, 0, buf.Length, flags, ref remote_end);
  1089. }
  1090. public int ReceiveFrom (byte [] buf, int size, SocketFlags flags,
  1091. ref EndPoint remote_end)
  1092. {
  1093. if (buf == null)
  1094. throw new ArgumentNullException ("buf");
  1095. if (remote_end == null)
  1096. throw new ArgumentNullException ("remote_end");
  1097. if (size < 0 || size > buf.Length)
  1098. throw new ArgumentOutOfRangeException ("size");
  1099. return ReceiveFrom_nochecks (buf, 0, size, flags, ref remote_end);
  1100. }
  1101. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1102. private extern static int RecvFrom_internal(IntPtr sock,
  1103. byte[] buffer,
  1104. int offset,
  1105. int count,
  1106. SocketFlags flags,
  1107. ref SocketAddress sockaddr,
  1108. out int error);
  1109. public int ReceiveFrom (byte [] buf, int offset, int size, SocketFlags flags,
  1110. ref EndPoint remote_end)
  1111. {
  1112. if (buf == null)
  1113. throw new ArgumentNullException ("buf");
  1114. if (remote_end == null)
  1115. throw new ArgumentNullException ("remote_end");
  1116. if (offset < 0 || offset > buf.Length)
  1117. throw new ArgumentOutOfRangeException ("offset");
  1118. if (size < 0 || offset + size > buf.Length)
  1119. throw new ArgumentOutOfRangeException ("size");
  1120. return ReceiveFrom_nochecks (buf, offset, size, flags, ref remote_end);
  1121. }
  1122. int ReceiveFrom_nochecks (byte [] buf, int offset, int size, SocketFlags flags,
  1123. ref EndPoint remote_end)
  1124. {
  1125. SocketAddress sockaddr = remote_end.Serialize();
  1126. int cnt, error;
  1127. cnt = RecvFrom_internal (socket, buf, offset, size, flags, ref sockaddr, out error);
  1128. if (error != 0) {
  1129. connected = false;
  1130. throw new SocketException (error);
  1131. }
  1132. connected = true;
  1133. // If sockaddr is null then we're a connection
  1134. // oriented protocol and should ignore the
  1135. // remote_end parameter (see MSDN
  1136. // documentation for Socket.ReceiveFrom(...) )
  1137. if ( sockaddr != null ) {
  1138. // Stupidly, EndPoint.Create() is an
  1139. // instance method
  1140. remote_end = remote_end.Create (sockaddr);
  1141. }
  1142. return cnt;
  1143. }
  1144. public int Send (byte [] buf)
  1145. {
  1146. if (buf == null)
  1147. throw new ArgumentNullException ("buf");
  1148. return Send_nochecks (buf, 0, buf.Length, SocketFlags.None);
  1149. }
  1150. public int Send (byte [] buf, SocketFlags flags)
  1151. {
  1152. if (buf == null)
  1153. throw new ArgumentNullException ("buf");
  1154. return Send_nochecks (buf, 0, buf.Length, flags);
  1155. }
  1156. public int Send (byte [] buf, int size, SocketFlags flags)
  1157. {
  1158. if (buf == null)
  1159. throw new ArgumentNullException ("buf");
  1160. if (size < 0 || size > buf.Length)
  1161. throw new ArgumentOutOfRangeException ("size");
  1162. return Send_nochecks (buf, 0, size, flags);
  1163. }
  1164. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1165. private extern static int Send_internal(IntPtr sock,
  1166. byte[] buf, int offset,
  1167. int count,
  1168. SocketFlags flags,
  1169. out int error);
  1170. public int Send (byte [] buf, int offset, int size, SocketFlags flags)
  1171. {
  1172. if (buf == null)
  1173. throw new ArgumentNullException ("buffer");
  1174. if (offset < 0 || offset > buf.Length)
  1175. throw new ArgumentOutOfRangeException ("offset");
  1176. if (size < 0 || offset + size > buf.Length)
  1177. throw new ArgumentOutOfRangeException ("size");
  1178. return Send_nochecks (buf, offset, size, flags);
  1179. }
  1180. int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags)
  1181. {
  1182. if (size == 0)
  1183. return 0;
  1184. int ret, error;
  1185. ret = Send_internal (socket, buf, offset, size, flags, out error);
  1186. if (error != 0) {
  1187. connected = false;
  1188. throw new SocketException (error);
  1189. }
  1190. connected = true;
  1191. return ret;
  1192. }
  1193. public int SendTo (byte [] buffer, EndPoint remote_end)
  1194. {
  1195. if (buffer == null)
  1196. throw new ArgumentNullException ("buffer");
  1197. if (remote_end == null)
  1198. throw new ArgumentNullException ("remote_end");
  1199. return SendTo_nochecks (buffer, 0, buffer.Length, SocketFlags.None, remote_end);
  1200. }
  1201. public int SendTo (byte [] buffer, SocketFlags flags, EndPoint remote_end)
  1202. {
  1203. if (buffer == null)
  1204. throw new ArgumentNullException ("buffer");
  1205. if (remote_end == null)
  1206. throw new ArgumentNullException ("remote_end");
  1207. return SendTo_nochecks (buffer, 0, buffer.Length, flags, remote_end);
  1208. }
  1209. public int SendTo (byte [] buffer, int size, SocketFlags flags, EndPoint remote_end)
  1210. {
  1211. if (buffer == null)
  1212. throw new ArgumentNullException ("buffer");
  1213. if (remote_end == null)
  1214. throw new ArgumentNullException ("remote_end");
  1215. if (size < 0 || size > buffer.Length)
  1216. throw new ArgumentOutOfRangeException ("size");
  1217. return SendTo_nochecks (buffer, 0, size, flags, remote_end);
  1218. }
  1219. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1220. private extern static int SendTo_internal(IntPtr sock,
  1221. byte[] buffer,
  1222. int offset,
  1223. int count,
  1224. SocketFlags flags,
  1225. SocketAddress sa,
  1226. out int error);
  1227. public int SendTo (byte [] buffer, int offset, int size, SocketFlags flags,
  1228. EndPoint remote_end)
  1229. {
  1230. if (buffer == null)
  1231. throw new ArgumentNullException ("buffer");
  1232. if (remote_end == null)
  1233. throw new ArgumentNullException("remote_end");
  1234. if (offset < 0 || offset > buffer.Length)
  1235. throw new ArgumentOutOfRangeException ("offset");
  1236. if (size < 0 || offset + size > buffer.Length)
  1237. throw new ArgumentOutOfRangeException ("size");
  1238. return SendTo_nochecks (buffer, offset, size, flags, remote_end);
  1239. }
  1240. int SendTo_nochecks (byte [] buffer, int offset, int size, SocketFlags flags,
  1241. EndPoint remote_end)
  1242. {
  1243. SocketAddress sockaddr = remote_end.Serialize ();
  1244. int ret, error;
  1245. ret = SendTo_internal (socket, buffer, offset, size, flags, sockaddr, out error);
  1246. if (error != 0) {
  1247. connected = false;
  1248. throw new SocketException (error);
  1249. }
  1250. connected = true;
  1251. return ret;
  1252. }
  1253. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1254. private extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level,
  1255. SocketOptionName name, object obj_val,
  1256. byte [] byte_val, int int_val,
  1257. out int error);
  1258. public void SetSocketOption(SocketOptionLevel level,
  1259. SocketOptionName name,
  1260. byte[] opt_value) {
  1261. int error;
  1262. SetSocketOption_internal(socket, level, name, null,
  1263. opt_value, 0, out error);
  1264. if (error != 0) {
  1265. throw new SocketException (error);
  1266. }
  1267. }
  1268. public void SetSocketOption(SocketOptionLevel level,
  1269. SocketOptionName name,
  1270. int opt_value) {
  1271. int error;
  1272. SetSocketOption_internal(socket, level, name, null,
  1273. null, opt_value, out error);
  1274. if (error != 0) {
  1275. throw new SocketException (error);
  1276. }
  1277. }
  1278. public void SetSocketOption(SocketOptionLevel level,
  1279. SocketOptionName name,
  1280. object opt_value) {
  1281. if(opt_value==null) {
  1282. throw new ArgumentNullException();
  1283. }
  1284. int error;
  1285. /* Passing a bool as the third parameter to
  1286. * SetSocketOption causes this overload to be
  1287. * used when in fact we want to pass the value
  1288. * to the runtime as an int.
  1289. */
  1290. if (opt_value is System.Boolean) {
  1291. bool bool_val = (bool) opt_value;
  1292. int int_val = (bool_val) ? 1 : 0;
  1293. SetSocketOption_internal (socket, level, name, null, null, int_val, out error);
  1294. } else {
  1295. SetSocketOption_internal (socket, level, name, opt_value, null, 0, out error);
  1296. }
  1297. if (error != 0) {
  1298. throw new SocketException (error);
  1299. }
  1300. }
  1301. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1302. private extern static void Shutdown_internal(IntPtr socket, SocketShutdown how, out int error);
  1303. public void Shutdown(SocketShutdown how) {
  1304. int error;
  1305. Shutdown_internal(socket, how, out error);
  1306. if (error != 0) {
  1307. throw new SocketException (error);
  1308. }
  1309. }
  1310. public override int GetHashCode ()
  1311. {
  1312. return (int) socket;
  1313. }
  1314. private bool disposed;
  1315. protected virtual void Dispose(bool explicitDisposing) {
  1316. if (!disposed) {
  1317. int error;
  1318. disposed = true;
  1319. connected = false;
  1320. if (!explicitDisposing) {
  1321. closed = true;
  1322. Close_internal (socket, out error);
  1323. if (error != 0) {
  1324. throw new SocketException (error);
  1325. }
  1326. return;
  1327. }
  1328. if (Interlocked.CompareExchange (ref pendingEnds, 0, 0) == 0) {
  1329. closed = true;
  1330. Close_internal (socket, out error);
  1331. if (error != 0) {
  1332. throw new SocketException (error);
  1333. }
  1334. } else {
  1335. Interlocked.CompareExchange (ref closeDelayed, 1, 0);
  1336. }
  1337. }
  1338. }
  1339. void IDisposable.Dispose ()
  1340. {
  1341. Dispose (true);
  1342. GC.SuppressFinalize (this);
  1343. }
  1344. ~Socket () {
  1345. Dispose(false);
  1346. }
  1347. static Hashtable asyncObjects;
  1348. static void KeepReference (object o)
  1349. {
  1350. lock (typeof (Socket)) {
  1351. if (asyncObjects == null)
  1352. asyncObjects = new Hashtable ();
  1353. asyncObjects [o] = o;
  1354. }
  1355. }
  1356. static void RemoveReference (object o)
  1357. {
  1358. lock (typeof (Socket)) {
  1359. if (asyncObjects == null)
  1360. return;
  1361. asyncObjects.Remove (o);
  1362. }
  1363. }
  1364. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1365. extern static bool GetSupportsAsync ();
  1366. static bool FakeGetSupportsAsync ()
  1367. {
  1368. if (Environment.GetEnvironmentVariable ("MONO_ENABLE_SOCKET_AIO") != null)
  1369. return GetSupportsAsync ();
  1370. return false;
  1371. }
  1372. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1373. extern static void AsyncReceiveInternal (SocketAsyncResult ares, out int error);
  1374. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1375. extern static void AsyncSendInternal (SocketAsyncResult ares, out int error);
  1376. }
  1377. }