Socket.cs 86 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294
  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. // Sridhar Kulkarni ([email protected])
  8. // Brian Nickel ([email protected])
  9. //
  10. // Copyright (C) 2001, 2002 Phillip Pearson and Ximian, Inc.
  11. // http://www.myelin.co.nz
  12. // (c) 2004-2006 Novell, Inc. (http://www.novell.com)
  13. //
  14. //
  15. // Permission is hereby granted, free of charge, to any person obtaining
  16. // a copy of this software and associated documentation files (the
  17. // "Software"), to deal in the Software without restriction, including
  18. // without limitation the rights to use, copy, modify, merge, publish,
  19. // distribute, sublicense, and/or sell copies of the Software, and to
  20. // permit persons to whom the Software is furnished to do so, subject to
  21. // the following conditions:
  22. //
  23. // The above copyright notice and this permission notice shall be
  24. // included in all copies or substantial portions of the Software.
  25. //
  26. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  27. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  28. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  29. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  30. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  31. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  32. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  33. //
  34. using System;
  35. using System.Net;
  36. using System.Collections;
  37. using System.Runtime.CompilerServices;
  38. using System.Runtime.InteropServices;
  39. using System.Threading;
  40. using System.Reflection;
  41. using System.IO;
  42. using System.Net.Configuration;
  43. using System.Text;
  44. #if NET_2_0
  45. using System.Collections.Generic;
  46. using System.Net.NetworkInformation;
  47. using System.Timers;
  48. #endif
  49. namespace System.Net.Sockets
  50. {
  51. public class Socket : IDisposable
  52. {
  53. enum SocketOperation {
  54. Accept,
  55. Connect,
  56. Receive,
  57. ReceiveFrom,
  58. Send,
  59. SendTo,
  60. UsedInManaged1,
  61. UsedInManaged2,
  62. UsedInProcess,
  63. UsedInConsole2,
  64. Disconnect,
  65. AcceptReceive
  66. }
  67. [StructLayout (LayoutKind.Sequential)]
  68. private sealed class SocketAsyncResult: IAsyncResult
  69. {
  70. /* Same structure in the runtime */
  71. public Socket Sock;
  72. public IntPtr handle;
  73. object state;
  74. AsyncCallback callback;
  75. WaitHandle waithandle;
  76. Exception delayedException;
  77. public EndPoint EndPoint; // Connect,ReceiveFrom,SendTo
  78. public byte [] Buffer; // Receive,ReceiveFrom,Send,SendTo
  79. public int Offset; // Receive,ReceiveFrom,Send,SendTo
  80. public int Size; // Receive,ReceiveFrom,Send,SendTo
  81. public SocketFlags SockFlags; // Receive,ReceiveFrom,Send,SendTo
  82. public Socket AcceptSocket; // AcceptReceive
  83. public IPAddress[] Addresses; // Connect
  84. public int Port; // Connect
  85. #if NET_2_0
  86. public IList<ArraySegment<byte>> Buffers; // Receive, Send
  87. #else
  88. public object Buffers; // Reserve this slot in older profiles
  89. #endif
  90. public bool ReuseSocket; // Disconnect
  91. // Return values
  92. Socket acc_socket;
  93. int total;
  94. bool completed_sync;
  95. bool completed;
  96. public bool blocking;
  97. internal int error;
  98. SocketOperation operation;
  99. public object ares;
  100. public SocketAsyncResult (Socket sock, object state, AsyncCallback callback, SocketOperation operation)
  101. {
  102. this.Sock = sock;
  103. this.blocking = sock.blocking;
  104. this.handle = sock.socket;
  105. this.state = state;
  106. this.callback = callback;
  107. this.operation = operation;
  108. SockFlags = SocketFlags.None;
  109. }
  110. public void CheckIfThrowDelayedException ()
  111. {
  112. if (delayedException != null) {
  113. throw delayedException;
  114. }
  115. if (error != 0)
  116. throw new SocketException (error);
  117. }
  118. void CompleteAllOnDispose (Queue queue)
  119. {
  120. object [] pending = queue.ToArray ();
  121. queue.Clear ();
  122. WaitCallback cb;
  123. for (int i = 0; i < pending.Length; i++) {
  124. SocketAsyncResult ares = (SocketAsyncResult) pending [i];
  125. cb = new WaitCallback (ares.CompleteDisposed);
  126. ThreadPool.QueueUserWorkItem (cb, null);
  127. }
  128. }
  129. void CompleteDisposed (object unused)
  130. {
  131. Complete ();
  132. }
  133. public void Complete ()
  134. {
  135. if (operation != SocketOperation.Receive && Sock.disposed)
  136. delayedException = new ObjectDisposedException (Sock.GetType ().ToString ());
  137. IsCompleted = true;
  138. Queue queue = null;
  139. if (operation == SocketOperation.Receive || operation == SocketOperation.ReceiveFrom) {
  140. queue = Sock.readQ;
  141. } else if (operation == SocketOperation.Send || operation == SocketOperation.SendTo) {
  142. queue = Sock.writeQ;
  143. }
  144. if (queue != null) {
  145. SocketAsyncCall sac = null;
  146. SocketAsyncResult req = null;
  147. lock (queue) {
  148. queue.Dequeue (); // remove ourselves
  149. if (queue.Count > 0) {
  150. req = (SocketAsyncResult) queue.Peek ();
  151. if (!Sock.disposed) {
  152. Worker worker = new Worker (req);
  153. sac = GetDelegate (worker, req.operation);
  154. } else {
  155. CompleteAllOnDispose (queue);
  156. }
  157. }
  158. }
  159. if (sac != null)
  160. sac.BeginInvoke (null, req);
  161. }
  162. if (callback != null)
  163. callback (this);
  164. }
  165. SocketAsyncCall GetDelegate (Worker worker, SocketOperation op)
  166. {
  167. switch (op) {
  168. case SocketOperation.Receive:
  169. return new SocketAsyncCall (worker.Receive);
  170. case SocketOperation.ReceiveFrom:
  171. return new SocketAsyncCall (worker.ReceiveFrom);
  172. case SocketOperation.Send:
  173. return new SocketAsyncCall (worker.Send);
  174. case SocketOperation.SendTo:
  175. return new SocketAsyncCall (worker.SendTo);
  176. default:
  177. return null; // never happens
  178. }
  179. }
  180. public void Complete (bool synch)
  181. {
  182. completed_sync = synch;
  183. Complete ();
  184. }
  185. public void Complete (int total)
  186. {
  187. this.total = total;
  188. Complete ();
  189. }
  190. public void Complete (Exception e, bool synch)
  191. {
  192. completed_sync = synch;
  193. delayedException = e;
  194. Complete ();
  195. }
  196. public void Complete (Exception e)
  197. {
  198. delayedException = e;
  199. Complete ();
  200. }
  201. public void Complete (Socket s)
  202. {
  203. acc_socket = s;
  204. Complete ();
  205. }
  206. public void Complete (Socket s, int total)
  207. {
  208. acc_socket = s;
  209. this.total = total;
  210. Complete ();
  211. }
  212. public object AsyncState {
  213. get {
  214. return state;
  215. }
  216. }
  217. public WaitHandle AsyncWaitHandle {
  218. get {
  219. lock (this) {
  220. if (waithandle == null)
  221. waithandle = new ManualResetEvent (completed);
  222. }
  223. return waithandle;
  224. }
  225. set {
  226. waithandle=value;
  227. }
  228. }
  229. public bool CompletedSynchronously {
  230. get {
  231. return(completed_sync);
  232. }
  233. }
  234. public bool IsCompleted {
  235. get {
  236. return(completed);
  237. }
  238. set {
  239. completed=value;
  240. lock (this) {
  241. if (waithandle != null && value) {
  242. ((ManualResetEvent) waithandle).Set ();
  243. }
  244. }
  245. }
  246. }
  247. public Socket Socket {
  248. get {
  249. return acc_socket;
  250. }
  251. }
  252. public int Total {
  253. get { return total; }
  254. set { total = value; }
  255. }
  256. public SocketError ErrorCode
  257. {
  258. get {
  259. #if NET_2_0
  260. SocketException ex = delayedException as SocketException;
  261. if (ex != null)
  262. return(ex.SocketErrorCode);
  263. if (error != 0)
  264. return((SocketError)error);
  265. #endif
  266. return(SocketError.Success);
  267. }
  268. }
  269. }
  270. private sealed class Worker
  271. {
  272. SocketAsyncResult result;
  273. public Worker (SocketAsyncResult ares)
  274. {
  275. this.result = ares;
  276. }
  277. public void Accept ()
  278. {
  279. Socket acc_socket = null;
  280. try {
  281. acc_socket = result.Sock.Accept ();
  282. } catch (Exception e) {
  283. result.Complete (e);
  284. return;
  285. }
  286. result.Complete (acc_socket);
  287. }
  288. /* only used in 2.0 profile and newer, but
  289. * leave in older profiles to keep interface
  290. * to runtime consistent
  291. */
  292. public void AcceptReceive ()
  293. {
  294. Socket acc_socket = null;
  295. try {
  296. if (result.AcceptSocket == null) {
  297. acc_socket = result.Sock.Accept ();
  298. } else {
  299. acc_socket = result.AcceptSocket;
  300. result.Sock.Accept (acc_socket);
  301. }
  302. } catch (Exception e) {
  303. result.Complete (e);
  304. return;
  305. }
  306. int total = 0;
  307. try {
  308. SocketError error;
  309. total = acc_socket.Receive_nochecks (result.Buffer,
  310. result.Offset,
  311. result.Size,
  312. result.SockFlags,
  313. out error);
  314. } catch (Exception e) {
  315. result.Complete (e);
  316. return;
  317. }
  318. result.Complete (acc_socket, total);
  319. }
  320. public void Connect ()
  321. {
  322. /* If result.EndPoint is non-null,
  323. * this is the standard one-address
  324. * connect attempt. Otherwise
  325. * Addresses must be non-null and
  326. * contain a list of addresses to try
  327. * to connect to; the first one to
  328. * succeed causes the rest of the list
  329. * to be ignored.
  330. */
  331. if (result.EndPoint != null) {
  332. try {
  333. if (!result.Sock.Blocking) {
  334. int success;
  335. result.Sock.Poll (-1, SelectMode.SelectWrite, out success);
  336. if (success == 0) {
  337. result.Sock.connected = true;
  338. } else {
  339. result.Complete (new SocketException (success));
  340. return;
  341. }
  342. } else {
  343. result.Sock.seed_endpoint = result.EndPoint;
  344. result.Sock.Connect (result.EndPoint);
  345. result.Sock.connected = true;
  346. }
  347. } catch (Exception e) {
  348. result.Complete (e);
  349. return;
  350. }
  351. result.Complete ();
  352. } else if (result.Addresses != null) {
  353. foreach(IPAddress address in result.Addresses) {
  354. IPEndPoint iep = new IPEndPoint (address, result.Port);
  355. SocketAddress serial = iep.Serialize ();
  356. int error = 0;
  357. Socket.Connect_internal (result.Sock.socket, serial, out error);
  358. if (error == 0) {
  359. result.Sock.connected = true;
  360. result.Sock.seed_endpoint = iep;
  361. result.Complete ();
  362. return;
  363. } else if (error != (int)SocketError.InProgress &&
  364. error != (int)SocketError.WouldBlock) {
  365. continue;
  366. }
  367. if (!result.Sock.Blocking) {
  368. int success;
  369. result.Sock.Poll (-1, SelectMode.SelectWrite, out success);
  370. if (success == 0) {
  371. result.Sock.connected = true;
  372. result.Sock.seed_endpoint = iep;
  373. result.Complete ();
  374. return;
  375. }
  376. }
  377. }
  378. result.Complete (new SocketException ((int)SocketError.InProgress));
  379. } else {
  380. result.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
  381. }
  382. }
  383. /* Also only used in 2.0 profile and newer */
  384. public void Disconnect ()
  385. {
  386. #if NET_2_0
  387. try {
  388. result.Sock.Disconnect (result.ReuseSocket);
  389. } catch (Exception e) {
  390. result.Complete (e);
  391. return;
  392. }
  393. result.Complete ();
  394. #else
  395. result.Complete (new SocketException ((int)SocketError.Fault));
  396. #endif
  397. }
  398. public void Receive ()
  399. {
  400. // Actual recv() done in the runtime
  401. result.Complete ();
  402. }
  403. public void ReceiveFrom ()
  404. {
  405. int total = 0;
  406. try {
  407. total = result.Sock.ReceiveFrom_nochecks (result.Buffer,
  408. result.Offset,
  409. result.Size,
  410. result.SockFlags,
  411. ref result.EndPoint);
  412. } catch (Exception e) {
  413. result.Complete (e);
  414. return;
  415. }
  416. result.Complete (total);
  417. }
  418. int send_so_far;
  419. void UpdateSendValues (int last_sent)
  420. {
  421. if (result.error == 0) {
  422. send_so_far += last_sent;
  423. result.Offset += last_sent;
  424. result.Size -= last_sent;
  425. }
  426. }
  427. public void Send ()
  428. {
  429. // Actual send() done in the runtime
  430. if (result.error == 0) {
  431. UpdateSendValues (result.Total);
  432. if (result.Sock.disposed) {
  433. result.Complete ();
  434. return;
  435. }
  436. if (result.Size > 0) {
  437. SocketAsyncCall sac = new SocketAsyncCall (this.Send);
  438. sac.BeginInvoke (null, result);
  439. return; // Have to finish writing everything. See bug #74475.
  440. }
  441. result.Total = send_so_far;
  442. }
  443. result.Complete ();
  444. }
  445. public void SendTo ()
  446. {
  447. int total = 0;
  448. try {
  449. total = result.Sock.SendTo_nochecks (result.Buffer,
  450. result.Offset,
  451. result.Size,
  452. result.SockFlags,
  453. result.EndPoint);
  454. UpdateSendValues (total);
  455. if (result.Size > 0) {
  456. SocketAsyncCall sac = new SocketAsyncCall (this.SendTo);
  457. sac.BeginInvoke (null, result);
  458. return; // Have to finish writing everything. See bug #74475.
  459. }
  460. result.Total = send_so_far;
  461. } catch (Exception e) {
  462. result.Complete (e);
  463. return;
  464. }
  465. result.Complete ();
  466. }
  467. }
  468. static Socket () {
  469. // initialize ipv4Supported and ipv6Supported
  470. CheckProtocolSupport ();
  471. }
  472. /* the field "socket" is looked up by name by the runtime */
  473. private IntPtr socket;
  474. private AddressFamily address_family;
  475. private SocketType socket_type;
  476. private ProtocolType protocol_type;
  477. internal bool blocking=true;
  478. private Queue readQ = new Queue (2);
  479. private Queue writeQ = new Queue (2);
  480. delegate void SocketAsyncCall ();
  481. /*
  482. * These two fields are looked up by name by the runtime, don't change
  483. * their name without also updating the runtime code.
  484. */
  485. private static int ipv4Supported = -1, ipv6Supported = -1;
  486. /* When true, the socket was connected at the time of
  487. * the last IO operation
  488. */
  489. private bool connected;
  490. /* true if we called Close_internal */
  491. private bool closed;
  492. internal bool disposed;
  493. /*
  494. * This EndPoint is used when creating new endpoints. Because
  495. * there are many types of EndPoints possible,
  496. * seed_endpoint.Create(addr) is used for creating new ones.
  497. * As such, this value is set on Bind, SentTo, ReceiveFrom,
  498. * Connect, etc.
  499. */
  500. private EndPoint seed_endpoint = null;
  501. #if NET_2_0
  502. private bool isbound;
  503. private bool islistening;
  504. private bool useoverlappedIO;
  505. #endif
  506. static void AddSockets (ArrayList sockets, IList list, string name)
  507. {
  508. if (list != null) {
  509. foreach (Socket sock in list) {
  510. if (sock == null) // MS throws a NullRef
  511. throw new ArgumentNullException ("name", "Contains a null element");
  512. sockets.Add (sock);
  513. }
  514. }
  515. sockets.Add (null);
  516. }
  517. #if !TARGET_JVM
  518. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  519. private extern static void Select_internal (ref Socket [] sockets,
  520. int microSeconds,
  521. out int error);
  522. #endif
  523. public static void Select (IList checkRead, IList checkWrite, IList checkError, int microSeconds)
  524. {
  525. ArrayList list = new ArrayList ();
  526. AddSockets (list, checkRead, "checkRead");
  527. AddSockets (list, checkWrite, "checkWrite");
  528. AddSockets (list, checkError, "checkError");
  529. if (list.Count == 3) {
  530. throw new ArgumentNullException ("checkRead, checkWrite, checkError",
  531. "All the lists are null or empty.");
  532. }
  533. int error;
  534. /*
  535. * The 'sockets' array contains: READ socket 0-n, null,
  536. * WRITE socket 0-n, null,
  537. * ERROR socket 0-n, null
  538. */
  539. Socket [] sockets = (Socket []) list.ToArray (typeof (Socket));
  540. Select_internal (ref sockets, microSeconds, out error);
  541. if (error != 0)
  542. throw new SocketException (error);
  543. if (checkRead != null)
  544. checkRead.Clear ();
  545. if (checkWrite != null)
  546. checkWrite.Clear ();
  547. if (checkError != null)
  548. checkError.Clear ();
  549. if (sockets == null)
  550. return;
  551. int mode = 0;
  552. int count = sockets.Length;
  553. IList currentList = checkRead;
  554. for (int i = 0; i < count; i++) {
  555. Socket sock = sockets [i];
  556. if (sock == null) { // separator
  557. currentList = (mode == 0) ? checkWrite : checkError;
  558. mode++;
  559. continue;
  560. }
  561. if (currentList != null) {
  562. if (currentList == checkWrite && !sock.connected) {
  563. if ((int) sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error) == 0) {
  564. sock.connected = true;
  565. }
  566. }
  567. currentList.Add (sock);
  568. }
  569. }
  570. }
  571. // private constructor used by Accept, which already
  572. // has a socket handle to use
  573. private Socket(AddressFamily family, SocketType type,
  574. ProtocolType proto, IntPtr sock)
  575. {
  576. address_family=family;
  577. socket_type=type;
  578. protocol_type=proto;
  579. socket=sock;
  580. connected=true;
  581. }
  582. #if !TARGET_JVM
  583. // Creates a new system socket, returning the handle
  584. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  585. private extern IntPtr Socket_internal(AddressFamily family,
  586. SocketType type,
  587. ProtocolType proto,
  588. out int error);
  589. #endif
  590. private void SocketDefaults ()
  591. {
  592. #if NET_2_0
  593. try {
  594. if (address_family == AddressFamily.InterNetwork /* Need to test IPv6 further ||
  595. address_family == AddressFamily.InterNetworkV6 */) {
  596. /* This is the default, but it
  597. * probably has nasty side
  598. * effects on Linux, as the
  599. * socket option is kludged by
  600. * turning on or off PMTU
  601. * discovery...
  602. */
  603. this.DontFragment = false;
  604. }
  605. //
  606. // Microsoft sets these to 8192, but we are going to keep them
  607. // both to the OS defaults as these have a big performance impact.
  608. // on WebClient performance.
  609. //
  610. //this.ReceiveBufferSize = 8192;
  611. //this.SendBufferSize = 8192;
  612. } catch (SocketException) {
  613. }
  614. #endif
  615. }
  616. public Socket(AddressFamily family, SocketType type, ProtocolType proto)
  617. {
  618. address_family=family;
  619. socket_type=type;
  620. protocol_type=proto;
  621. int error;
  622. socket = Socket_internal (family, type, proto, out error);
  623. if (error != 0)
  624. throw new SocketException (error);
  625. SocketDefaults ();
  626. }
  627. #if NET_2_0
  628. [MonoTODO]
  629. public Socket (SocketInformation socketInformation)
  630. {
  631. throw new NotImplementedException ("SocketInformation not figured out yet");
  632. // ifdef to avoid the warnings.
  633. #if false
  634. //address_family = socketInformation.address_family;
  635. //socket_type = socketInformation.socket_type;
  636. //protocol_type = socketInformation.protocol_type;
  637. address_family = AddressFamily.InterNetwork;
  638. socket_type = SocketType.Stream;
  639. protocol_type = ProtocolType.IP;
  640. int error;
  641. socket = Socket_internal (address_family, socket_type, protocol_type, out error);
  642. if (error != 0)
  643. throw new SocketException (error);
  644. SocketDefaults ();
  645. #endif
  646. }
  647. #endif
  648. public AddressFamily AddressFamily {
  649. get {
  650. return(address_family);
  651. }
  652. }
  653. #if !TARGET_JVM
  654. // Returns the amount of data waiting to be read on socket
  655. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  656. private extern static int Available_internal(IntPtr socket, out int error);
  657. #endif
  658. public int Available {
  659. get {
  660. if (disposed && closed)
  661. throw new ObjectDisposedException (GetType ().ToString ());
  662. int ret, error;
  663. ret = Available_internal(socket, out error);
  664. if (error != 0)
  665. throw new SocketException (error);
  666. return(ret);
  667. }
  668. }
  669. #if !TARGET_JVM
  670. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  671. private extern static void Blocking_internal(IntPtr socket,
  672. bool block,
  673. out int error);
  674. #endif
  675. public bool Blocking {
  676. get {
  677. return(blocking);
  678. }
  679. set {
  680. if (disposed && closed)
  681. throw new ObjectDisposedException (GetType ().ToString ());
  682. int error;
  683. Blocking_internal (socket, value, out error);
  684. if (error != 0)
  685. throw new SocketException (error);
  686. blocking=value;
  687. }
  688. }
  689. public bool Connected {
  690. get {
  691. return(connected);
  692. }
  693. }
  694. #if NET_2_0
  695. public bool DontFragment {
  696. get {
  697. if (disposed && closed) {
  698. throw new ObjectDisposedException (GetType ().ToString ());
  699. }
  700. bool dontfragment;
  701. if (address_family == AddressFamily.InterNetwork) {
  702. dontfragment = (int)(GetSocketOption (SocketOptionLevel.IP, SocketOptionName.DontFragment)) != 0;
  703. } else if (address_family == AddressFamily.InterNetworkV6) {
  704. dontfragment = (int)(GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DontFragment)) != 0;
  705. } else {
  706. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  707. }
  708. return(dontfragment);
  709. }
  710. set {
  711. if (disposed && closed) {
  712. throw new ObjectDisposedException (GetType ().ToString ());
  713. }
  714. if (address_family == AddressFamily.InterNetwork) {
  715. SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DontFragment, value?1:0);
  716. } else if (address_family == AddressFamily.InterNetworkV6) {
  717. SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DontFragment, value?1:0);
  718. } else {
  719. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  720. }
  721. }
  722. }
  723. public bool EnableBroadcast {
  724. get {
  725. if (disposed && closed) {
  726. throw new ObjectDisposedException (GetType ().ToString ());
  727. }
  728. if (protocol_type != ProtocolType.Udp) {
  729. throw new SocketException ((int)SocketError.ProtocolOption);
  730. }
  731. return((int)(GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast)) != 0);
  732. }
  733. set {
  734. if (disposed && closed) {
  735. throw new ObjectDisposedException (GetType ().ToString ());
  736. }
  737. if (protocol_type != ProtocolType.Udp) {
  738. throw new SocketException ((int)SocketError.ProtocolOption);
  739. }
  740. SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, value?1:0);
  741. }
  742. }
  743. public bool ExclusiveAddressUse {
  744. get {
  745. if (disposed && closed) {
  746. throw new ObjectDisposedException (GetType ().ToString ());
  747. }
  748. return((int)(GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse)) != 0);
  749. }
  750. set {
  751. if (disposed && closed) {
  752. throw new ObjectDisposedException (GetType ().ToString ());
  753. }
  754. if (isbound) {
  755. throw new InvalidOperationException ("Bind has already been called for this socket");
  756. }
  757. SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, value?1:0);
  758. }
  759. }
  760. public bool IsBound {
  761. get {
  762. return(isbound);
  763. }
  764. }
  765. public LingerOption LingerState {
  766. get {
  767. if (disposed && closed) {
  768. throw new ObjectDisposedException (GetType ().ToString ());
  769. }
  770. return((LingerOption)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger));
  771. }
  772. set {
  773. if (disposed && closed) {
  774. throw new ObjectDisposedException (GetType ().ToString ());
  775. }
  776. SetSocketOption (SocketOptionLevel.Socket,
  777. SocketOptionName.Linger,
  778. value);
  779. }
  780. }
  781. public bool MulticastLoopback {
  782. get {
  783. if (disposed && closed) {
  784. throw new ObjectDisposedException (GetType ().ToString ());
  785. }
  786. /* Even though this option can be set
  787. * for TCP sockets on Linux, throw
  788. * this exception anyway to be
  789. * compatible (the MSDN docs say
  790. * "Setting this property on a
  791. * Transmission Control Protocol (TCP)
  792. * socket will have no effect." but
  793. * the MS runtime throws the
  794. * exception...)
  795. */
  796. if (protocol_type == ProtocolType.Tcp) {
  797. throw new SocketException ((int)SocketError.ProtocolOption);
  798. }
  799. bool multicastloopback;
  800. if (address_family == AddressFamily.InterNetwork) {
  801. multicastloopback = (int)(GetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback)) != 0;
  802. } else if (address_family == AddressFamily.InterNetworkV6) {
  803. multicastloopback = (int)(GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback)) != 0;
  804. } else {
  805. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  806. }
  807. return(multicastloopback);
  808. }
  809. set {
  810. if (disposed && closed) {
  811. throw new ObjectDisposedException (GetType ().ToString ());
  812. }
  813. /* Even though this option can be set
  814. * for TCP sockets on Linux, throw
  815. * this exception anyway to be
  816. * compatible (the MSDN docs say
  817. * "Setting this property on a
  818. * Transmission Control Protocol (TCP)
  819. * socket will have no effect." but
  820. * the MS runtime throws the
  821. * exception...)
  822. */
  823. if (protocol_type == ProtocolType.Tcp) {
  824. throw new SocketException ((int)SocketError.ProtocolOption);
  825. }
  826. if (address_family == AddressFamily.InterNetwork) {
  827. SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, value?1:0);
  828. } else if (address_family == AddressFamily.InterNetworkV6) {
  829. SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback, value?1:0);
  830. } else {
  831. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  832. }
  833. }
  834. }
  835. public static bool OSSupportsIPv6 {
  836. get {
  837. NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
  838. foreach(NetworkInterface adapter in nics) {
  839. if (adapter.Supports (NetworkInterfaceComponent.IPv6) == true) {
  840. return(true);
  841. } else {
  842. continue;
  843. }
  844. }
  845. return(false);
  846. }
  847. }
  848. public int ReceiveBufferSize {
  849. get {
  850. if (disposed && closed) {
  851. throw new ObjectDisposedException (GetType ().ToString ());
  852. }
  853. return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer));
  854. }
  855. set {
  856. if (disposed && closed) {
  857. throw new ObjectDisposedException (GetType ().ToString ());
  858. }
  859. if (value < 0) {
  860. throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
  861. }
  862. SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
  863. }
  864. }
  865. public int SendBufferSize {
  866. get {
  867. if (disposed && closed) {
  868. throw new ObjectDisposedException (GetType ().ToString ());
  869. }
  870. return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer));
  871. }
  872. set {
  873. if (disposed && closed) {
  874. throw new ObjectDisposedException (GetType ().ToString ());
  875. }
  876. if (value < 0) {
  877. throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
  878. }
  879. SetSocketOption (SocketOptionLevel.Socket,
  880. SocketOptionName.SendBuffer,
  881. value);
  882. }
  883. }
  884. public short Ttl {
  885. get {
  886. if (disposed && closed) {
  887. throw new ObjectDisposedException (GetType ().ToString ());
  888. }
  889. short ttl_val;
  890. if (address_family == AddressFamily.InterNetwork) {
  891. ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive));
  892. } else if (address_family == AddressFamily.InterNetworkV6) {
  893. ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit));
  894. } else {
  895. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  896. }
  897. return(ttl_val);
  898. }
  899. set {
  900. if (disposed && closed) {
  901. throw new ObjectDisposedException (GetType ().ToString ());
  902. }
  903. if (address_family == AddressFamily.InterNetwork) {
  904. SetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, value);
  905. } else if (address_family == AddressFamily.InterNetworkV6) {
  906. SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit, value);
  907. } else {
  908. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  909. }
  910. }
  911. }
  912. [MonoTODO ("This doesn't do anything on Mono yet")]
  913. public bool UseOnlyOverlappedIO {
  914. get {
  915. return(useoverlappedIO);
  916. }
  917. set {
  918. useoverlappedIO = value;
  919. }
  920. }
  921. #endif
  922. public IntPtr Handle {
  923. get {
  924. return(socket);
  925. }
  926. }
  927. #if !TARGET_JVM
  928. // Returns the local endpoint details in addr and port
  929. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  930. private extern static SocketAddress LocalEndPoint_internal(IntPtr socket, out int error);
  931. #endif
  932. // Wish: support non-IP endpoints.
  933. public EndPoint LocalEndPoint {
  934. get {
  935. if (disposed && closed)
  936. throw new ObjectDisposedException (GetType ().ToString ());
  937. /*
  938. * If the seed EndPoint is null, Connect, Bind,
  939. * etc has not yet been called. MS returns null
  940. * in this case.
  941. */
  942. if (seed_endpoint == null)
  943. return null;
  944. SocketAddress sa;
  945. int error;
  946. sa=LocalEndPoint_internal(socket, out error);
  947. if (error != 0)
  948. throw new SocketException (error);
  949. return seed_endpoint.Create (sa);
  950. }
  951. }
  952. public ProtocolType ProtocolType {
  953. get {
  954. return(protocol_type);
  955. }
  956. }
  957. // Returns the remote endpoint details in addr and port
  958. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  959. private extern static SocketAddress RemoteEndPoint_internal(IntPtr socket, out int error);
  960. public EndPoint RemoteEndPoint {
  961. get {
  962. if (disposed && closed)
  963. throw new ObjectDisposedException (GetType ().ToString ());
  964. /*
  965. * If the seed EndPoint is null, Connect, Bind,
  966. * etc has not yet been called. MS returns null
  967. * in this case.
  968. */
  969. if (seed_endpoint == null)
  970. return null;
  971. SocketAddress sa;
  972. int error;
  973. sa=RemoteEndPoint_internal(socket, out error);
  974. if (error != 0)
  975. throw new SocketException (error);
  976. return seed_endpoint.Create (sa);
  977. }
  978. }
  979. public SocketType SocketType {
  980. get {
  981. return(socket_type);
  982. }
  983. }
  984. public static bool SupportsIPv4 {
  985. get {
  986. CheckProtocolSupport();
  987. return ipv4Supported == 1;
  988. }
  989. }
  990. #if NET_2_0
  991. [ObsoleteAttribute ("Use OSSupportsIPv6 instead")]
  992. #endif
  993. public static bool SupportsIPv6 {
  994. get {
  995. CheckProtocolSupport();
  996. return ipv6Supported == 1;
  997. }
  998. }
  999. #if NET_2_0
  1000. public int SendTimeout {
  1001. get {
  1002. if (disposed && closed)
  1003. throw new ObjectDisposedException (GetType ().ToString ());
  1004. return (int)GetSocketOption(
  1005. SocketOptionLevel.Socket,
  1006. SocketOptionName.SendTimeout);
  1007. }
  1008. set {
  1009. if (disposed && closed)
  1010. throw new ObjectDisposedException (GetType ().ToString ());
  1011. if (value < -1)
  1012. throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than -1");
  1013. /* According to the MSDN docs we
  1014. * should adjust values between 1 and
  1015. * 499 to 500, but the MS runtime
  1016. * doesn't do this.
  1017. */
  1018. if (value == -1)
  1019. value = 0;
  1020. SetSocketOption(
  1021. SocketOptionLevel.Socket,
  1022. SocketOptionName.SendTimeout, value);
  1023. }
  1024. }
  1025. public int ReceiveTimeout {
  1026. get {
  1027. if (disposed && closed)
  1028. throw new ObjectDisposedException (GetType ().ToString ());
  1029. return (int)GetSocketOption(
  1030. SocketOptionLevel.Socket,
  1031. SocketOptionName.ReceiveTimeout);
  1032. }
  1033. set {
  1034. if (disposed && closed)
  1035. throw new ObjectDisposedException (GetType ().ToString ());
  1036. if (value < -1)
  1037. throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than -1");
  1038. if (value == -1) {
  1039. value = 0;
  1040. }
  1041. SetSocketOption(
  1042. SocketOptionLevel.Socket,
  1043. SocketOptionName.ReceiveTimeout, value);
  1044. }
  1045. }
  1046. public bool NoDelay {
  1047. get {
  1048. if (disposed && closed)
  1049. throw new ObjectDisposedException (GetType ().ToString ());
  1050. if (protocol_type == ProtocolType.Udp)
  1051. throw new SocketException ((int)SocketError.ProtocolOption);
  1052. return (int)(GetSocketOption (
  1053. SocketOptionLevel.Tcp,
  1054. SocketOptionName.NoDelay)) != 0;
  1055. }
  1056. set {
  1057. if (disposed && closed)
  1058. throw new ObjectDisposedException (GetType ().ToString ());
  1059. if (protocol_type == ProtocolType.Udp)
  1060. throw new SocketException ((int)SocketError.ProtocolOption);
  1061. SetSocketOption (
  1062. SocketOptionLevel.Tcp,
  1063. SocketOptionName.NoDelay, value ? 1 : 0);
  1064. }
  1065. }
  1066. #endif
  1067. internal static void CheckProtocolSupport ()
  1068. {
  1069. if(ipv4Supported == -1) {
  1070. try {
  1071. Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  1072. tmp.Close();
  1073. ipv4Supported = 1;
  1074. } catch {
  1075. ipv4Supported = 0;
  1076. }
  1077. }
  1078. if (ipv6Supported == -1) {
  1079. #if NET_2_0 && CONFIGURATION_DEP
  1080. SettingsSection config;
  1081. config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
  1082. if (config != null)
  1083. ipv6Supported = config.Ipv6.Enabled ? -1 : 0;
  1084. #else
  1085. NetConfig config = (NetConfig)System.Configuration.ConfigurationSettings.GetConfig("system.net/settings");
  1086. if (config != null)
  1087. ipv6Supported = config.ipv6Enabled ? -1 : 0;
  1088. #endif
  1089. if (ipv6Supported != 0) {
  1090. try {
  1091. Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
  1092. tmp.Close();
  1093. ipv6Supported = 1;
  1094. } catch { }
  1095. }
  1096. }
  1097. }
  1098. // Creates a new system socket, returning the handle
  1099. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1100. private extern static IntPtr Accept_internal(IntPtr sock, out int error);
  1101. Thread blocking_thread;
  1102. public Socket Accept() {
  1103. if (disposed && closed)
  1104. throw new ObjectDisposedException (GetType ().ToString ());
  1105. int error = 0;
  1106. IntPtr sock = (IntPtr) (-1);
  1107. blocking_thread = Thread.CurrentThread;
  1108. try {
  1109. sock = Accept_internal(socket, out error);
  1110. } catch (ThreadAbortException) {
  1111. if (disposed) {
  1112. Thread.ResetAbort ();
  1113. error = (int) SocketError.Interrupted;
  1114. }
  1115. } finally {
  1116. blocking_thread = null;
  1117. }
  1118. if (error != 0)
  1119. throw new SocketException (error);
  1120. Socket accepted = new Socket(this.AddressFamily, this.SocketType,
  1121. this.ProtocolType, sock);
  1122. accepted.seed_endpoint = this.seed_endpoint;
  1123. accepted.Blocking = this.Blocking;
  1124. return(accepted);
  1125. }
  1126. private void Accept (Socket acceptSocket)
  1127. {
  1128. if (disposed && closed)
  1129. throw new ObjectDisposedException (GetType ().ToString ());
  1130. int error = 0;
  1131. IntPtr sock = (IntPtr)(-1);
  1132. blocking_thread = Thread.CurrentThread;
  1133. try {
  1134. sock = Accept_internal (socket, out error);
  1135. } catch (ThreadAbortException) {
  1136. if (disposed) {
  1137. Thread.ResetAbort ();
  1138. error = (int)SocketError.Interrupted;
  1139. }
  1140. } finally {
  1141. blocking_thread = null;
  1142. }
  1143. if (error != 0)
  1144. throw new SocketException (error);
  1145. acceptSocket.address_family = this.AddressFamily;
  1146. acceptSocket.socket_type = this.SocketType;
  1147. acceptSocket.protocol_type = this.ProtocolType;
  1148. acceptSocket.socket = sock;
  1149. acceptSocket.connected = true;
  1150. acceptSocket.seed_endpoint = this.seed_endpoint;
  1151. acceptSocket.Blocking = this.Blocking;
  1152. /* FIXME: figure out what if anything else
  1153. * needs to be reset
  1154. */
  1155. }
  1156. public IAsyncResult BeginAccept(AsyncCallback callback,
  1157. object state)
  1158. {
  1159. if (disposed && closed)
  1160. throw new ObjectDisposedException (GetType ().ToString ());
  1161. #if NET_2_0
  1162. /* FIXME: check the 1.1 docs for this too */
  1163. if (!isbound || !islistening)
  1164. throw new InvalidOperationException ();
  1165. #endif
  1166. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Accept);
  1167. Worker worker = new Worker (req);
  1168. SocketAsyncCall sac = new SocketAsyncCall (worker.Accept);
  1169. sac.BeginInvoke (null, req);
  1170. return(req);
  1171. }
  1172. #if NET_2_0
  1173. public IAsyncResult BeginAccept (int receiveSize,
  1174. AsyncCallback callback,
  1175. object state)
  1176. {
  1177. if (disposed && closed)
  1178. throw new ObjectDisposedException (GetType ().ToString ());
  1179. if (receiveSize < 0)
  1180. throw new ArgumentOutOfRangeException ("receiveSize", "receiveSize is less than zero");
  1181. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.AcceptReceive);
  1182. Worker worker = new Worker (req);
  1183. SocketAsyncCall sac = new SocketAsyncCall (worker.AcceptReceive);
  1184. req.Buffer = new byte[receiveSize];
  1185. req.Offset = 0;
  1186. req.Size = receiveSize;
  1187. req.SockFlags = SocketFlags.None;
  1188. sac.BeginInvoke (null, req);
  1189. return(req);
  1190. }
  1191. public IAsyncResult BeginAccept (Socket acceptSocket,
  1192. int receiveSize,
  1193. AsyncCallback callback,
  1194. object state)
  1195. {
  1196. if (disposed && closed)
  1197. throw new ObjectDisposedException (GetType ().ToString ());
  1198. if (receiveSize < 0)
  1199. throw new ArgumentOutOfRangeException ("receiveSize", "receiveSize is less than zero");
  1200. if (acceptSocket != null) {
  1201. if (acceptSocket.disposed && acceptSocket.closed)
  1202. throw new ObjectDisposedException (acceptSocket.GetType ().ToString ());
  1203. if (acceptSocket.IsBound)
  1204. throw new InvalidOperationException ();
  1205. /* For some reason the MS runtime
  1206. * barfs if the new socket is not TCP,
  1207. * even though it's just about to blow
  1208. * away all those parameters
  1209. */
  1210. if (acceptSocket.ProtocolType != ProtocolType.Tcp)
  1211. throw new SocketException ((int)SocketError.InvalidArgument);
  1212. }
  1213. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.AcceptReceive);
  1214. Worker worker = new Worker (req);
  1215. SocketAsyncCall sac = new SocketAsyncCall (worker.AcceptReceive);
  1216. req.Buffer = new byte[receiveSize];
  1217. req.Offset = 0;
  1218. req.Size = receiveSize;
  1219. req.SockFlags = SocketFlags.None;
  1220. req.AcceptSocket = acceptSocket;
  1221. sac.BeginInvoke (null, req);
  1222. return(req);
  1223. }
  1224. #endif
  1225. public IAsyncResult BeginConnect(EndPoint end_point,
  1226. AsyncCallback callback,
  1227. object state) {
  1228. if (disposed && closed)
  1229. throw new ObjectDisposedException (GetType ().ToString ());
  1230. if (end_point == null)
  1231. throw new ArgumentNullException ("end_point");
  1232. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
  1233. req.EndPoint = end_point;
  1234. // Bug #75154: Connect() should not succeed for .Any addresses.
  1235. if (end_point is IPEndPoint) {
  1236. IPEndPoint ep = (IPEndPoint) end_point;
  1237. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
  1238. req.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
  1239. return req;
  1240. }
  1241. }
  1242. int error = 0;
  1243. if (!blocking) {
  1244. SocketAddress serial = end_point.Serialize ();
  1245. Connect_internal (socket, serial, out error);
  1246. if (error == 0) {
  1247. // succeeded synch
  1248. connected = true;
  1249. req.Complete (true);
  1250. } else if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
  1251. // error synch
  1252. connected = false;
  1253. req.Complete (new SocketException (error), true);
  1254. }
  1255. }
  1256. if (blocking || error == (int) SocketError.InProgress || error == (int) SocketError.WouldBlock) {
  1257. // continue asynch
  1258. connected = false;
  1259. Worker worker = new Worker (req);
  1260. SocketAsyncCall sac = new SocketAsyncCall (worker.Connect);
  1261. sac.BeginInvoke (null, req);
  1262. }
  1263. return(req);
  1264. }
  1265. #if NET_2_0
  1266. public IAsyncResult BeginConnect (IPAddress address, int port,
  1267. AsyncCallback callback,
  1268. object state)
  1269. {
  1270. if (disposed && closed)
  1271. throw new ObjectDisposedException (GetType ().ToString ());
  1272. if (address == null)
  1273. throw new ArgumentNullException ("address");
  1274. if (address.ToString ().Length == 0)
  1275. throw new ArgumentException ("The length of the IP address is zero");
  1276. if (islistening)
  1277. throw new InvalidOperationException ();
  1278. IPEndPoint iep = new IPEndPoint (address, port);
  1279. return(BeginConnect (iep, callback, state));
  1280. }
  1281. public IAsyncResult BeginConnect (IPAddress[] addresses,
  1282. int port,
  1283. AsyncCallback callback,
  1284. object state)
  1285. {
  1286. if (disposed && closed)
  1287. throw new ObjectDisposedException (GetType ().ToString ());
  1288. if (addresses == null)
  1289. throw new ArgumentNullException ("addresses");
  1290. if (this.AddressFamily != AddressFamily.InterNetwork &&
  1291. this.AddressFamily != AddressFamily.InterNetworkV6)
  1292. throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
  1293. if (islistening)
  1294. throw new InvalidOperationException ();
  1295. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
  1296. req.Addresses = addresses;
  1297. req.Port = port;
  1298. connected = false;
  1299. Worker worker = new Worker (req);
  1300. SocketAsyncCall sac = new SocketAsyncCall (worker.Connect);
  1301. sac.BeginInvoke (null, req);
  1302. return(req);
  1303. }
  1304. public IAsyncResult BeginConnect (string host, int port,
  1305. AsyncCallback callback,
  1306. object state)
  1307. {
  1308. if (disposed && closed)
  1309. throw new ObjectDisposedException (GetType ().ToString ());
  1310. if (host == null)
  1311. throw new ArgumentNullException ("host");
  1312. if (address_family != AddressFamily.InterNetwork &&
  1313. address_family != AddressFamily.InterNetworkV6)
  1314. throw new NotSupportedException ("This method is valid only for sockets in the InterNetwork and InterNetworkV6 families");
  1315. if (islistening)
  1316. throw new InvalidOperationException ();
  1317. IPHostEntry hostent = Dns.GetHostEntry (host);
  1318. return (BeginConnect (hostent.AddressList, port, callback, state));
  1319. }
  1320. public IAsyncResult BeginDisconnect (bool reuseSocket,
  1321. AsyncCallback callback,
  1322. object state)
  1323. {
  1324. if (disposed && closed)
  1325. throw new ObjectDisposedException (GetType ().ToString ());
  1326. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Disconnect);
  1327. req.ReuseSocket = reuseSocket;
  1328. Worker worker = new Worker (req);
  1329. SocketAsyncCall sac = new SocketAsyncCall (worker.Disconnect);
  1330. sac.BeginInvoke (null, req);
  1331. return(req);
  1332. }
  1333. #endif
  1334. public IAsyncResult BeginReceive(byte[] buffer, int offset,
  1335. int size,
  1336. SocketFlags socket_flags,
  1337. AsyncCallback callback,
  1338. object state) {
  1339. if (disposed && closed)
  1340. throw new ObjectDisposedException (GetType ().ToString ());
  1341. if (buffer == null)
  1342. throw new ArgumentNullException ("buffer");
  1343. if (offset < 0 || offset > buffer.Length)
  1344. throw new ArgumentOutOfRangeException ("offset");
  1345. if (size < 0 || offset + size > buffer.Length)
  1346. throw new ArgumentOutOfRangeException ("size");
  1347. SocketAsyncResult req;
  1348. lock (readQ) {
  1349. req = new SocketAsyncResult (this, state, callback, SocketOperation.Receive);
  1350. req.Buffer = buffer;
  1351. req.Offset = offset;
  1352. req.Size = size;
  1353. req.SockFlags = socket_flags;
  1354. readQ.Enqueue (req);
  1355. if (readQ.Count == 1) {
  1356. Worker worker = new Worker (req);
  1357. SocketAsyncCall sac = new SocketAsyncCall (worker.Receive);
  1358. sac.BeginInvoke (null, req);
  1359. }
  1360. }
  1361. return req;
  1362. }
  1363. #if NET_2_0
  1364. public IAsyncResult BeginReceive (byte[] buffer, int offset,
  1365. int size, SocketFlags flags,
  1366. out SocketError error,
  1367. AsyncCallback callback,
  1368. object state)
  1369. {
  1370. /* As far as I can tell from the docs and from
  1371. * experimentation, a pointer to the
  1372. * SocketError parameter is not supposed to be
  1373. * saved for the async parts. And as we don't
  1374. * set any socket errors in the setup code, we
  1375. * just have to set it to Success.
  1376. */
  1377. error = SocketError.Success;
  1378. return (BeginReceive (buffer, offset, size, flags, callback, state));
  1379. }
  1380. [CLSCompliant (false)]
  1381. public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers,
  1382. SocketFlags socketFlags,
  1383. AsyncCallback callback,
  1384. object state)
  1385. {
  1386. if (disposed && closed)
  1387. throw new ObjectDisposedException (GetType ().ToString ());
  1388. if (buffers == null)
  1389. throw new ArgumentNullException ("buffers");
  1390. SocketAsyncResult req;
  1391. lock(readQ) {
  1392. req = new SocketAsyncResult (this, state, callback, SocketOperation.Receive);
  1393. req.Buffers = buffers;
  1394. req.SockFlags = socketFlags;
  1395. readQ.Enqueue (req);
  1396. if (readQ.Count == 1) {
  1397. Worker worker = new Worker (req);
  1398. SocketAsyncCall sac = new SocketAsyncCall (worker.Receive);
  1399. sac.BeginInvoke (null, req);
  1400. }
  1401. }
  1402. return(req);
  1403. }
  1404. [CLSCompliant (false)]
  1405. public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers,
  1406. SocketFlags socketFlags,
  1407. out SocketError errorCode,
  1408. AsyncCallback callback,
  1409. object state)
  1410. {
  1411. /* I assume the same SocketError semantics as
  1412. * above
  1413. */
  1414. errorCode = SocketError.Success;
  1415. return (BeginReceive (buffers, socketFlags, callback, state));
  1416. }
  1417. #endif
  1418. public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset,
  1419. int size,
  1420. SocketFlags socket_flags,
  1421. ref EndPoint remote_end,
  1422. AsyncCallback callback,
  1423. object state) {
  1424. if (disposed && closed)
  1425. throw new ObjectDisposedException (GetType ().ToString ());
  1426. if (buffer == null)
  1427. throw new ArgumentNullException ("buffer");
  1428. if (offset < 0)
  1429. throw new ArgumentOutOfRangeException ("offset", "offset must be >= 0");
  1430. if (size < 0)
  1431. throw new ArgumentOutOfRangeException ("size", "size must be >= 0");
  1432. if (offset + size > buffer.Length)
  1433. throw new ArgumentOutOfRangeException ("offset, size", "offset + size exceeds the buffer length");
  1434. SocketAsyncResult req;
  1435. lock (readQ) {
  1436. req = new SocketAsyncResult (this, state, callback, SocketOperation.ReceiveFrom);
  1437. req.Buffer = buffer;
  1438. req.Offset = offset;
  1439. req.Size = size;
  1440. req.SockFlags = socket_flags;
  1441. req.EndPoint = remote_end;
  1442. readQ.Enqueue (req);
  1443. if (readQ.Count == 1) {
  1444. Worker worker = new Worker (req);
  1445. SocketAsyncCall sac = new SocketAsyncCall (worker.ReceiveFrom);
  1446. sac.BeginInvoke (null, req);
  1447. }
  1448. }
  1449. return req;
  1450. }
  1451. #if NET_2_0
  1452. [MonoTODO]
  1453. public IAsyncResult BeginReceiveMessageFrom (
  1454. byte[] buffer, int offset, int size,
  1455. SocketFlags socketFlags, ref EndPoint remoteEP,
  1456. AsyncCallback callback, object state)
  1457. {
  1458. if (disposed && closed)
  1459. throw new ObjectDisposedException (GetType ().ToString ());
  1460. if (buffer == null)
  1461. throw new ArgumentNullException ("buffer");
  1462. if (remoteEP == null)
  1463. throw new ArgumentNullException ("remoteEP");
  1464. if (offset < 0 || offset > buffer.Length)
  1465. throw new ArgumentOutOfRangeException ("offset");
  1466. if (size < 0 || offset + size > buffer.Length)
  1467. throw new ArgumentOutOfRangeException ("size");
  1468. throw new NotImplementedException ();
  1469. }
  1470. #endif
  1471. public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socket_flags,
  1472. AsyncCallback callback, object state)
  1473. {
  1474. if (disposed && closed)
  1475. throw new ObjectDisposedException (GetType ().ToString ());
  1476. if (buffer == null)
  1477. throw new ArgumentNullException ("buffer");
  1478. if (offset < 0)
  1479. throw new ArgumentOutOfRangeException ("offset", "offset must be >= 0");
  1480. if (size < 0)
  1481. throw new ArgumentOutOfRangeException ("size", "size must be >= 0");
  1482. if (offset + size > buffer.Length)
  1483. throw new ArgumentOutOfRangeException ("offset, size", "offset + size exceeds the buffer length");
  1484. #if NET_2_0
  1485. /* TODO: Check this exception in the 1.1 profile */
  1486. if (!connected)
  1487. throw new SocketException ((int)SocketError.NotConnected);
  1488. #endif
  1489. SocketAsyncResult req;
  1490. lock (writeQ) {
  1491. req = new SocketAsyncResult (this, state, callback, SocketOperation.Send);
  1492. req.Buffer = buffer;
  1493. req.Offset = offset;
  1494. req.Size = size;
  1495. req.SockFlags = socket_flags;
  1496. writeQ.Enqueue (req);
  1497. if (writeQ.Count == 1) {
  1498. Worker worker = new Worker (req);
  1499. SocketAsyncCall sac = new SocketAsyncCall (worker.Send);
  1500. sac.BeginInvoke (null, req);
  1501. }
  1502. }
  1503. return req;
  1504. }
  1505. #if NET_2_0
  1506. public IAsyncResult BeginSend (byte[] buffer, int offset,
  1507. int size,
  1508. SocketFlags socketFlags,
  1509. out SocketError errorCode,
  1510. AsyncCallback callback,
  1511. object state)
  1512. {
  1513. if (!connected) {
  1514. errorCode = SocketError.NotConnected;
  1515. throw new SocketException ((int)errorCode);
  1516. }
  1517. errorCode = SocketError.Success;
  1518. return (BeginSend (buffer, offset, size, socketFlags, callback,
  1519. state));
  1520. }
  1521. public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers,
  1522. SocketFlags socketFlags,
  1523. AsyncCallback callback,
  1524. object state)
  1525. {
  1526. if (disposed && closed)
  1527. throw new ObjectDisposedException (GetType ().ToString ());
  1528. if (buffers == null)
  1529. throw new ArgumentNullException ("buffers");
  1530. if (!connected)
  1531. throw new SocketException ((int)SocketError.NotConnected);
  1532. SocketAsyncResult req;
  1533. lock (writeQ) {
  1534. req = new SocketAsyncResult (this, state, callback, SocketOperation.Send);
  1535. req.Buffers = buffers;
  1536. req.SockFlags = socketFlags;
  1537. writeQ.Enqueue (req);
  1538. if (writeQ.Count == 1) {
  1539. Worker worker = new Worker (req);
  1540. SocketAsyncCall sac = new SocketAsyncCall (worker.Send);
  1541. sac.BeginInvoke (null, req);
  1542. }
  1543. }
  1544. return(req);
  1545. }
  1546. [CLSCompliant (false)]
  1547. public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers,
  1548. SocketFlags socketFlags,
  1549. out SocketError errorCode,
  1550. AsyncCallback callback,
  1551. object state)
  1552. {
  1553. if (!connected) {
  1554. errorCode = SocketError.NotConnected;
  1555. throw new SocketException ((int)errorCode);
  1556. }
  1557. errorCode = SocketError.Success;
  1558. return (BeginSend (buffers, socketFlags, callback, state));
  1559. }
  1560. [MonoTODO ("Not implemented")]
  1561. public IAsyncResult BeginSendFile (string fileName,
  1562. AsyncCallback callback,
  1563. object state)
  1564. {
  1565. if (disposed && closed)
  1566. throw new ObjectDisposedException (GetType ().ToString ());
  1567. if (!connected)
  1568. throw new NotSupportedException ();
  1569. if (!File.Exists (fileName))
  1570. throw new FileNotFoundException ();
  1571. throw new NotImplementedException ();
  1572. }
  1573. [MonoTODO ("Not implemented")]
  1574. public IAsyncResult BeginSendFile (string fileName,
  1575. byte[] preBuffer,
  1576. byte[] postBuffer,
  1577. TransmitFileOptions flags,
  1578. AsyncCallback callback,
  1579. object state)
  1580. {
  1581. if (disposed && closed)
  1582. throw new ObjectDisposedException (GetType ().ToString ());
  1583. if (!connected)
  1584. throw new NotSupportedException ();
  1585. if (!File.Exists (fileName))
  1586. throw new FileNotFoundException ();
  1587. throw new NotImplementedException ();
  1588. }
  1589. #endif
  1590. public IAsyncResult BeginSendTo(byte[] buffer, int offset,
  1591. int size,
  1592. SocketFlags socket_flags,
  1593. EndPoint remote_end,
  1594. AsyncCallback callback,
  1595. object state) {
  1596. if (disposed && closed)
  1597. throw new ObjectDisposedException (GetType ().ToString ());
  1598. if (buffer == null)
  1599. throw new ArgumentNullException ("buffer");
  1600. if (offset < 0)
  1601. throw new ArgumentOutOfRangeException ("offset", "offset must be >= 0");
  1602. if (size < 0)
  1603. throw new ArgumentOutOfRangeException ("size", "size must be >= 0");
  1604. if (offset + size > buffer.Length)
  1605. throw new ArgumentOutOfRangeException ("offset, size", "offset + size exceeds the buffer length");
  1606. SocketAsyncResult req;
  1607. lock (writeQ) {
  1608. req = new SocketAsyncResult (this, state, callback, SocketOperation.SendTo);
  1609. req.Buffer = buffer;
  1610. req.Offset = offset;
  1611. req.Size = size;
  1612. req.SockFlags = socket_flags;
  1613. req.EndPoint = remote_end;
  1614. writeQ.Enqueue (req);
  1615. if (writeQ.Count == 1) {
  1616. Worker worker = new Worker (req);
  1617. SocketAsyncCall sac = new SocketAsyncCall (worker.SendTo);
  1618. sac.BeginInvoke (null, req);
  1619. }
  1620. }
  1621. return req;
  1622. }
  1623. // Creates a new system socket, returning the handle
  1624. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1625. private extern static void Bind_internal(IntPtr sock,
  1626. SocketAddress sa,
  1627. out int error);
  1628. public void Bind(EndPoint local_end) {
  1629. if (disposed && closed)
  1630. throw new ObjectDisposedException (GetType ().ToString ());
  1631. if (local_end == null)
  1632. throw new ArgumentNullException("local_end");
  1633. int error;
  1634. Bind_internal(socket, local_end.Serialize(), out error);
  1635. if (error != 0)
  1636. throw new SocketException (error);
  1637. #if NET_2_0
  1638. if (error == 0)
  1639. isbound = true;
  1640. #endif
  1641. seed_endpoint = local_end;
  1642. }
  1643. // Closes the socket
  1644. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1645. private extern static void Close_internal(IntPtr socket, out int error);
  1646. public void Close()
  1647. {
  1648. ((IDisposable) this).Dispose ();
  1649. }
  1650. #if NET_2_0
  1651. public void Close (int timeout)
  1652. {
  1653. System.Timers.Timer close_timer = new System.Timers.Timer ();
  1654. close_timer.Elapsed += new ElapsedEventHandler (OnTimeoutClose);
  1655. close_timer.Interval = timeout * 1000;
  1656. close_timer.AutoReset = false;
  1657. close_timer.Enabled = true;
  1658. }
  1659. private void OnTimeoutClose (object source, ElapsedEventArgs e)
  1660. {
  1661. this.Close ();
  1662. }
  1663. #endif
  1664. // Connects to the remote address
  1665. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1666. private extern static void Connect_internal(IntPtr sock,
  1667. SocketAddress sa,
  1668. out int error);
  1669. public void Connect(EndPoint remote_end) {
  1670. if (disposed && closed)
  1671. throw new ObjectDisposedException (GetType ().ToString ());
  1672. if (remote_end == null)
  1673. throw new ArgumentNullException("remote_end");
  1674. if (remote_end is IPEndPoint) {
  1675. IPEndPoint ep = (IPEndPoint) remote_end;
  1676. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
  1677. throw new SocketException ((int) SocketError.AddressNotAvailable);
  1678. }
  1679. #if NET_2_0
  1680. /* TODO: check this for the 1.1 profile too */
  1681. if (islistening)
  1682. throw new InvalidOperationException ();
  1683. #endif
  1684. SocketAddress serial = remote_end.Serialize ();
  1685. int error = 0;
  1686. blocking_thread = Thread.CurrentThread;
  1687. try {
  1688. Connect_internal (socket, serial, out error);
  1689. } catch (ThreadAbortException) {
  1690. if (disposed) {
  1691. Thread.ResetAbort ();
  1692. error = (int) SocketError.Interrupted;
  1693. }
  1694. } finally {
  1695. blocking_thread = null;
  1696. }
  1697. if (error != 0)
  1698. throw new SocketException (error);
  1699. connected=true;
  1700. #if NET_2_0
  1701. isbound = true;
  1702. #endif
  1703. seed_endpoint = remote_end;
  1704. }
  1705. #if NET_2_0
  1706. public void Connect (IPAddress address, int port)
  1707. {
  1708. Connect (new IPEndPoint (address, port));
  1709. }
  1710. public void Connect (IPAddress[] addresses, int port)
  1711. {
  1712. if (disposed && closed)
  1713. throw new ObjectDisposedException (GetType ().ToString ());
  1714. if (addresses == null)
  1715. throw new ArgumentNullException ("addresses");
  1716. if (this.AddressFamily != AddressFamily.InterNetwork &&
  1717. this.AddressFamily != AddressFamily.InterNetworkV6)
  1718. throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
  1719. if (islistening)
  1720. throw new InvalidOperationException ();
  1721. /* FIXME: do non-blocking sockets Poll here? */
  1722. foreach (IPAddress address in addresses) {
  1723. IPEndPoint iep = new IPEndPoint (address,
  1724. port);
  1725. SocketAddress serial = iep.Serialize ();
  1726. int error = 0;
  1727. Connect_internal (socket, serial, out error);
  1728. if (error == 0) {
  1729. connected = true;
  1730. seed_endpoint = iep;
  1731. return;
  1732. } else if (error != (int)SocketError.InProgress &&
  1733. error != (int)SocketError.WouldBlock) {
  1734. continue;
  1735. }
  1736. if (!blocking) {
  1737. Poll (-1, SelectMode.SelectWrite);
  1738. int success = (int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
  1739. if (success == 0) {
  1740. connected = true;
  1741. seed_endpoint = iep;
  1742. return;
  1743. }
  1744. }
  1745. }
  1746. }
  1747. public void Connect (string host, int port)
  1748. {
  1749. IPHostEntry hostent = Dns.GetHostEntry (host);
  1750. Connect (hostent.AddressList, port);
  1751. }
  1752. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1753. private extern static void Disconnect_internal(IntPtr sock,
  1754. bool reuse,
  1755. out int error);
  1756. /* According to the docs, the MS runtime will throw
  1757. * PlatformNotSupportedException if the platform is
  1758. * newer than w2k. We should be able to cope...
  1759. */
  1760. public void Disconnect (bool reuseSocket)
  1761. {
  1762. if (disposed && closed)
  1763. throw new ObjectDisposedException (GetType ().ToString ());
  1764. int error = 0;
  1765. Disconnect_internal (socket, reuseSocket, out error);
  1766. if (error != 0) {
  1767. if (error == 50) {
  1768. /* ERROR_NOT_SUPPORTED */
  1769. throw new PlatformNotSupportedException ();
  1770. } else {
  1771. throw new SocketException (error);
  1772. }
  1773. }
  1774. connected = false;
  1775. if (reuseSocket) {
  1776. /* Do managed housekeeping here... */
  1777. }
  1778. }
  1779. [MonoTODO ("Not implemented")]
  1780. public SocketInformation DuplicateAndClose (int targetProcessId)
  1781. {
  1782. /* Need to serialize this socket into a
  1783. * SocketInformation struct, but must study
  1784. * the MS implementation harder to figure out
  1785. * behaviour as documentation is lacking
  1786. */
  1787. throw new NotImplementedException ();
  1788. }
  1789. #endif
  1790. public Socket EndAccept (IAsyncResult result)
  1791. {
  1792. int bytes;
  1793. byte[] buffer;
  1794. return(EndAccept (out buffer, out bytes, result));
  1795. }
  1796. #if NET_2_0
  1797. public Socket EndAccept (out byte[] buffer,
  1798. IAsyncResult asyncResult)
  1799. {
  1800. int bytes;
  1801. return(EndAccept (out buffer, out bytes, asyncResult));
  1802. }
  1803. #endif
  1804. #if NET_2_0
  1805. public
  1806. #else
  1807. private
  1808. #endif
  1809. Socket EndAccept (out byte[] buffer, out int bytesTransferred,
  1810. IAsyncResult asyncResult)
  1811. {
  1812. if (disposed && closed)
  1813. throw new ObjectDisposedException (GetType ().ToString ());
  1814. if (asyncResult == null)
  1815. throw new ArgumentNullException ("asyncResult");
  1816. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  1817. if (req == null)
  1818. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  1819. if (!asyncResult.IsCompleted)
  1820. asyncResult.AsyncWaitHandle.WaitOne ();
  1821. req.CheckIfThrowDelayedException ();
  1822. buffer = req.Buffer;
  1823. bytesTransferred = req.Total;
  1824. return(req.Socket);
  1825. }
  1826. public void EndConnect (IAsyncResult result)
  1827. {
  1828. if (disposed && closed)
  1829. throw new ObjectDisposedException (GetType ().ToString ());
  1830. if (result == null)
  1831. throw new ArgumentNullException ("result");
  1832. SocketAsyncResult req = result as SocketAsyncResult;
  1833. if (req == null)
  1834. throw new ArgumentException ("Invalid IAsyncResult", "result");
  1835. if (!result.IsCompleted)
  1836. result.AsyncWaitHandle.WaitOne();
  1837. req.CheckIfThrowDelayedException();
  1838. }
  1839. #if NET_2_0
  1840. public void EndDisconnect (IAsyncResult asyncResult)
  1841. {
  1842. if (disposed && closed)
  1843. throw new ObjectDisposedException (GetType ().ToString ());
  1844. if (asyncResult == null)
  1845. throw new ArgumentNullException ("asyncResult");
  1846. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  1847. if (req == null)
  1848. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  1849. if (!asyncResult.IsCompleted)
  1850. asyncResult.AsyncWaitHandle.WaitOne ();
  1851. req.CheckIfThrowDelayedException ();
  1852. }
  1853. #endif
  1854. public int EndReceive (IAsyncResult result)
  1855. {
  1856. SocketError error;
  1857. return (EndReceive (result, out error));
  1858. }
  1859. #if NET_2_0
  1860. public
  1861. #else
  1862. private
  1863. #endif
  1864. int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
  1865. {
  1866. if (disposed && closed)
  1867. throw new ObjectDisposedException (GetType ().ToString ());
  1868. if (asyncResult == null)
  1869. throw new ArgumentNullException ("asyncResult");
  1870. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  1871. if (req == null)
  1872. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  1873. if (!asyncResult.IsCompleted)
  1874. asyncResult.AsyncWaitHandle.WaitOne ();
  1875. errorCode = req.ErrorCode;
  1876. req.CheckIfThrowDelayedException ();
  1877. return(req.Total);
  1878. }
  1879. public int EndReceiveFrom(IAsyncResult result, ref EndPoint end_point)
  1880. {
  1881. if (disposed && closed)
  1882. throw new ObjectDisposedException (GetType ().ToString ());
  1883. if (result == null)
  1884. throw new ArgumentNullException ("result");
  1885. SocketAsyncResult req = result as SocketAsyncResult;
  1886. if (req == null)
  1887. throw new ArgumentException ("Invalid IAsyncResult", "result");
  1888. if (!result.IsCompleted)
  1889. result.AsyncWaitHandle.WaitOne();
  1890. req.CheckIfThrowDelayedException();
  1891. end_point = req.EndPoint;
  1892. return req.Total;
  1893. }
  1894. #if NET_2_0
  1895. [MonoTODO]
  1896. public int EndReceiveMessageFrom (IAsyncResult asyncResult,
  1897. ref SocketFlags socketFlags,
  1898. ref EndPoint endPoint,
  1899. out IPPacketInformation ipPacketInformation)
  1900. {
  1901. if (disposed && closed)
  1902. throw new ObjectDisposedException (GetType ().ToString ());
  1903. if (asyncResult == null)
  1904. throw new ArgumentNullException ("asyncResult");
  1905. if (endPoint == null)
  1906. throw new ArgumentNullException ("endPoint");
  1907. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  1908. if (req == null)
  1909. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  1910. throw new NotImplementedException ();
  1911. }
  1912. #endif
  1913. public int EndSend (IAsyncResult result)
  1914. {
  1915. SocketError error;
  1916. return(EndSend (result, out error));
  1917. }
  1918. #if NET_2_0
  1919. public
  1920. #else
  1921. private
  1922. #endif
  1923. int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
  1924. {
  1925. if (disposed && closed)
  1926. throw new ObjectDisposedException (GetType ().ToString ());
  1927. if (asyncResult == null)
  1928. throw new ArgumentNullException ("asyncResult");
  1929. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  1930. if (req == null)
  1931. throw new ArgumentException ("Invalid IAsyncResult", "result");
  1932. if (!asyncResult.IsCompleted)
  1933. asyncResult.AsyncWaitHandle.WaitOne ();
  1934. errorCode = req.ErrorCode;
  1935. req.CheckIfThrowDelayedException ();
  1936. return(req.Total);
  1937. }
  1938. #if NET_2_0
  1939. [MonoTODO]
  1940. public void EndSendFile (IAsyncResult asyncResult)
  1941. {
  1942. if (disposed && closed)
  1943. throw new ObjectDisposedException (GetType ().ToString ());
  1944. if (asyncResult == null)
  1945. throw new ArgumentNullException ("asyncResult");
  1946. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  1947. if (req == null)
  1948. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  1949. throw new NotImplementedException ();
  1950. }
  1951. #endif
  1952. public int EndSendTo (IAsyncResult result)
  1953. {
  1954. if (disposed && closed)
  1955. throw new ObjectDisposedException (GetType ().ToString ());
  1956. if (result == null)
  1957. throw new ArgumentNullException ("result");
  1958. SocketAsyncResult req = result as SocketAsyncResult;
  1959. if (req == null)
  1960. throw new ArgumentException ("Invalid IAsyncResult", "result");
  1961. if (!result.IsCompleted)
  1962. result.AsyncWaitHandle.WaitOne();
  1963. req.CheckIfThrowDelayedException();
  1964. return req.Total;
  1965. }
  1966. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1967. private extern static void GetSocketOption_obj_internal(IntPtr socket,
  1968. SocketOptionLevel level, SocketOptionName name, out object obj_val,
  1969. out int error);
  1970. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1971. private extern static void GetSocketOption_arr_internal(IntPtr socket,
  1972. SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val,
  1973. out int error);
  1974. public object GetSocketOption (SocketOptionLevel level, SocketOptionName name)
  1975. {
  1976. if (disposed && closed)
  1977. throw new ObjectDisposedException (GetType ().ToString ());
  1978. object obj_val;
  1979. int error;
  1980. GetSocketOption_obj_internal(socket, level, name, out obj_val,
  1981. out error);
  1982. if (error != 0)
  1983. throw new SocketException (error);
  1984. if (name == SocketOptionName.Linger) {
  1985. return((LingerOption)obj_val);
  1986. } else if (name==SocketOptionName.AddMembership ||
  1987. name==SocketOptionName.DropMembership) {
  1988. return((MulticastOption)obj_val);
  1989. } else if (obj_val is int) {
  1990. return((int)obj_val);
  1991. } else {
  1992. return(obj_val);
  1993. }
  1994. }
  1995. public void GetSocketOption (SocketOptionLevel level, SocketOptionName name, byte [] opt_value)
  1996. {
  1997. if (disposed && closed)
  1998. throw new ObjectDisposedException (GetType ().ToString ());
  1999. int error;
  2000. GetSocketOption_arr_internal(socket, level, name, ref opt_value,
  2001. out error);
  2002. if (error != 0)
  2003. throw new SocketException (error);
  2004. }
  2005. public byte [] GetSocketOption (SocketOptionLevel level, SocketOptionName name, int length)
  2006. {
  2007. if (disposed && closed)
  2008. throw new ObjectDisposedException (GetType ().ToString ());
  2009. byte[] byte_val=new byte[length];
  2010. int error;
  2011. GetSocketOption_arr_internal(socket, level, name, ref byte_val,
  2012. out error);
  2013. if (error != 0)
  2014. throw new SocketException (error);
  2015. return(byte_val);
  2016. }
  2017. // See Socket.IOControl, WSAIoctl documentation in MSDN. The
  2018. // common options between UNIX and Winsock are FIONREAD,
  2019. // FIONBIO and SIOCATMARK. Anything else will depend on the
  2020. // system.
  2021. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2022. extern static int WSAIoctl (IntPtr sock, int ioctl_code, byte [] input,
  2023. byte [] output, out int error);
  2024. public int IOControl (int ioctl_code, byte [] in_value, byte [] out_value)
  2025. {
  2026. if (disposed)
  2027. throw new ObjectDisposedException (GetType ().ToString ());
  2028. int error;
  2029. int result = WSAIoctl (socket, ioctl_code, in_value, out_value,
  2030. out error);
  2031. if (error != 0)
  2032. throw new SocketException (error);
  2033. if (result == -1)
  2034. throw new InvalidOperationException ("Must use Blocking property instead.");
  2035. return result;
  2036. }
  2037. #if NET_2_0
  2038. [MonoTODO]
  2039. public int IOControl (IOControlCode ioControlCode,
  2040. byte[] optionInValue,
  2041. byte[] optionOutValue)
  2042. {
  2043. /* Probably just needs to mirror the int
  2044. * overload, but more investigation needed.
  2045. */
  2046. throw new NotImplementedException ();
  2047. }
  2048. #endif
  2049. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2050. private extern static void Listen_internal(IntPtr sock, int backlog,
  2051. out int error);
  2052. public void Listen (int backlog)
  2053. {
  2054. if (disposed && closed)
  2055. throw new ObjectDisposedException (GetType ().ToString ());
  2056. #if NET_2_0
  2057. /* TODO: check if this should be thrown in the
  2058. * 1.1 profile too
  2059. */
  2060. if (!isbound)
  2061. throw new SocketException ((int)SocketError.InvalidArgument);
  2062. #endif
  2063. int error;
  2064. Listen_internal(socket, backlog, out error);
  2065. if (error != 0)
  2066. throw new SocketException (error);
  2067. #if NET_2_0
  2068. islistening = true;
  2069. #endif
  2070. }
  2071. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2072. extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
  2073. public bool Poll (int time_us, SelectMode mode)
  2074. {
  2075. if (disposed && closed)
  2076. throw new ObjectDisposedException (GetType ().ToString ());
  2077. if (mode != SelectMode.SelectRead &&
  2078. mode != SelectMode.SelectWrite &&
  2079. mode != SelectMode.SelectError)
  2080. throw new NotSupportedException ("'mode' parameter is not valid.");
  2081. int error;
  2082. bool result = Poll_internal (socket, mode, time_us, out error);
  2083. if (error != 0)
  2084. throw new SocketException (error);
  2085. if (mode == SelectMode.SelectWrite && result && !connected) {
  2086. /* Update the connected state; for
  2087. * non-blocking Connect()s this is
  2088. * when we can find out that the
  2089. * connect succeeded.
  2090. */
  2091. if ((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error) == 0) {
  2092. connected = true;
  2093. }
  2094. }
  2095. return result;
  2096. }
  2097. /* This overload is needed as the async Connect method
  2098. * also needs to check the socket error status, but
  2099. * getsockopt(..., SO_ERROR) clears the error.
  2100. */
  2101. private bool Poll (int time_us, SelectMode mode, out int socket_error)
  2102. {
  2103. if (disposed && closed)
  2104. throw new ObjectDisposedException (GetType ().ToString ());
  2105. if (mode != SelectMode.SelectRead &&
  2106. mode != SelectMode.SelectWrite &&
  2107. mode != SelectMode.SelectError)
  2108. throw new NotSupportedException ("'mode' parameter is not valid.");
  2109. int error;
  2110. bool result = Poll_internal (socket, mode, time_us, out error);
  2111. if (error != 0)
  2112. throw new SocketException (error);
  2113. socket_error = (int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
  2114. if (mode == SelectMode.SelectWrite && result) {
  2115. /* Update the connected state; for
  2116. * non-blocking Connect()s this is
  2117. * when we can find out that the
  2118. * connect succeeded.
  2119. */
  2120. if (socket_error == 0) {
  2121. connected = true;
  2122. }
  2123. }
  2124. return result;
  2125. }
  2126. public int Receive (byte [] buf)
  2127. {
  2128. if (disposed && closed)
  2129. throw new ObjectDisposedException (GetType ().ToString ());
  2130. if (buf == null)
  2131. throw new ArgumentNullException ("buf");
  2132. SocketError error;
  2133. int ret = Receive_nochecks (buf, 0, buf.Length, SocketFlags.None, out error);
  2134. if (error != SocketError.Success)
  2135. throw new SocketException ((int) error);
  2136. return ret;
  2137. }
  2138. public int Receive (byte [] buf, SocketFlags flags)
  2139. {
  2140. if (disposed && closed)
  2141. throw new ObjectDisposedException (GetType ().ToString ());
  2142. if (buf == null)
  2143. throw new ArgumentNullException ("buf");
  2144. SocketError error;
  2145. int ret = Receive_nochecks (buf, 0, buf.Length, flags, out error);
  2146. if (error != SocketError.Success) {
  2147. if (error == SocketError.WouldBlock && blocking) // This might happen when ReceiveTimeout is set
  2148. throw new SocketException ((int) error, "Operation timed out.");
  2149. throw new SocketException ((int) error);
  2150. }
  2151. return ret;
  2152. }
  2153. public int Receive (byte [] buf, int size, SocketFlags flags)
  2154. {
  2155. if (disposed && closed)
  2156. throw new ObjectDisposedException (GetType ().ToString ());
  2157. if (buf == null)
  2158. throw new ArgumentNullException ("buf");
  2159. if (size < 0 || size > buf.Length)
  2160. throw new ArgumentOutOfRangeException ("size");
  2161. SocketError error;
  2162. int ret = Receive_nochecks (buf, 0, size, flags, out error);
  2163. if (error != SocketError.Success) {
  2164. if (error == SocketError.WouldBlock && blocking) // This might happen when ReceiveTimeout is set
  2165. throw new SocketException ((int) error, "Operation timed out.");
  2166. throw new SocketException ((int) error);
  2167. }
  2168. return ret;
  2169. }
  2170. public int Receive (byte [] buf, int offset, int size, SocketFlags flags)
  2171. {
  2172. if (disposed && closed)
  2173. throw new ObjectDisposedException (GetType ().ToString ());
  2174. if (buf == null)
  2175. throw new ArgumentNullException ("buf");
  2176. if (offset < 0 || offset > buf.Length)
  2177. throw new ArgumentOutOfRangeException ("offset");
  2178. if (size < 0 || offset + size > buf.Length)
  2179. throw new ArgumentOutOfRangeException ("size");
  2180. SocketError error;
  2181. int ret = Receive_nochecks (buf, offset, size, flags, out error);
  2182. if (error != SocketError.Success) {
  2183. if (error == SocketError.WouldBlock && blocking) // This might happen when ReceiveTimeout is set
  2184. throw new SocketException ((int) error, "Operation timed out.");
  2185. throw new SocketException ((int) error);
  2186. }
  2187. return ret;
  2188. }
  2189. #if NET_2_0
  2190. public int Receive (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  2191. {
  2192. if (disposed && closed)
  2193. throw new ObjectDisposedException (GetType ().ToString ());
  2194. if (buf == null)
  2195. throw new ArgumentNullException ("buf");
  2196. if (offset < 0 || offset > buf.Length)
  2197. throw new ArgumentOutOfRangeException ("offset");
  2198. if (size < 0 || offset + size > buf.Length)
  2199. throw new ArgumentOutOfRangeException ("size");
  2200. return Receive_nochecks (buf, offset, size, flags, out error);
  2201. }
  2202. [MonoTODO]
  2203. public int Receive (IList<ArraySegment<byte>> buffers)
  2204. {
  2205. /* For these generic IList overloads I need to
  2206. * implement WSARecv in the runtime
  2207. */
  2208. throw new NotImplementedException ();
  2209. }
  2210. [CLSCompliant (false)]
  2211. [MonoTODO]
  2212. public int Receive (IList<ArraySegment<byte>> buffers,
  2213. SocketFlags socketFlags)
  2214. {
  2215. throw new NotImplementedException ();
  2216. }
  2217. [CLSCompliant (false)]
  2218. [MonoTODO]
  2219. public int Receive (IList<ArraySegment<byte>> buffers,
  2220. SocketFlags socketFlags,
  2221. out SocketError errorCode)
  2222. {
  2223. throw new NotImplementedException ();
  2224. }
  2225. #endif
  2226. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2227. private extern static int Receive_internal(IntPtr sock,
  2228. byte[] buffer,
  2229. int offset,
  2230. int count,
  2231. SocketFlags flags,
  2232. out int error);
  2233. int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  2234. {
  2235. int nativeError;
  2236. int ret = Receive_internal (socket, buf, offset, size, flags, out nativeError);
  2237. error = (SocketError) nativeError;
  2238. if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress)
  2239. connected = false;
  2240. else
  2241. connected = true;
  2242. return ret;
  2243. }
  2244. public int ReceiveFrom (byte [] buf, ref EndPoint remote_end)
  2245. {
  2246. if (disposed && closed)
  2247. throw new ObjectDisposedException (GetType ().ToString ());
  2248. if (buf == null)
  2249. throw new ArgumentNullException ("buf");
  2250. if (remote_end == null)
  2251. throw new ArgumentNullException ("remote_end");
  2252. return ReceiveFrom_nochecks (buf, 0, buf.Length, SocketFlags.None, ref remote_end);
  2253. }
  2254. public int ReceiveFrom (byte [] buf, SocketFlags flags, ref EndPoint remote_end)
  2255. {
  2256. if (disposed && closed)
  2257. throw new ObjectDisposedException (GetType ().ToString ());
  2258. if (buf == null)
  2259. throw new ArgumentNullException ("buf");
  2260. if (remote_end == null)
  2261. throw new ArgumentNullException ("remote_end");
  2262. return ReceiveFrom_nochecks (buf, 0, buf.Length, flags, ref remote_end);
  2263. }
  2264. public int ReceiveFrom (byte [] buf, int size, SocketFlags flags,
  2265. ref EndPoint remote_end)
  2266. {
  2267. if (disposed && closed)
  2268. throw new ObjectDisposedException (GetType ().ToString ());
  2269. if (buf == null)
  2270. throw new ArgumentNullException ("buf");
  2271. if (remote_end == null)
  2272. throw new ArgumentNullException ("remote_end");
  2273. if (size < 0 || size > buf.Length)
  2274. throw new ArgumentOutOfRangeException ("size");
  2275. return ReceiveFrom_nochecks (buf, 0, size, flags, ref remote_end);
  2276. }
  2277. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2278. private extern static int RecvFrom_internal(IntPtr sock,
  2279. byte[] buffer,
  2280. int offset,
  2281. int count,
  2282. SocketFlags flags,
  2283. ref SocketAddress sockaddr,
  2284. out int error);
  2285. public int ReceiveFrom (byte [] buf, int offset, int size, SocketFlags flags,
  2286. ref EndPoint remote_end)
  2287. {
  2288. if (disposed && closed)
  2289. throw new ObjectDisposedException (GetType ().ToString ());
  2290. if (buf == null)
  2291. throw new ArgumentNullException ("buf");
  2292. if (remote_end == null)
  2293. throw new ArgumentNullException ("remote_end");
  2294. if (offset < 0 || offset > buf.Length)
  2295. throw new ArgumentOutOfRangeException ("offset");
  2296. if (size < 0 || offset + size > buf.Length)
  2297. throw new ArgumentOutOfRangeException ("size");
  2298. return ReceiveFrom_nochecks (buf, offset, size, flags, ref remote_end);
  2299. }
  2300. int ReceiveFrom_nochecks (byte [] buf, int offset, int size, SocketFlags flags,
  2301. ref EndPoint remote_end)
  2302. {
  2303. SocketAddress sockaddr = remote_end.Serialize();
  2304. int cnt, error;
  2305. cnt = RecvFrom_internal (socket, buf, offset, size, flags, ref sockaddr, out error);
  2306. SocketError err = (SocketError) error;
  2307. if (err != 0) {
  2308. if (err != SocketError.WouldBlock && err != SocketError.InProgress)
  2309. connected = false;
  2310. else if (err == SocketError.WouldBlock && blocking) // This might happen when ReceiveTimeout is set
  2311. throw new SocketException (error, "Operation timed out.");
  2312. throw new SocketException (error);
  2313. }
  2314. connected = true;
  2315. #if NET_2_0
  2316. isbound = true;
  2317. #endif
  2318. // If sockaddr is null then we're a connection
  2319. // oriented protocol and should ignore the
  2320. // remote_end parameter (see MSDN
  2321. // documentation for Socket.ReceiveFrom(...) )
  2322. if ( sockaddr != null ) {
  2323. // Stupidly, EndPoint.Create() is an
  2324. // instance method
  2325. remote_end = remote_end.Create (sockaddr);
  2326. }
  2327. seed_endpoint = remote_end;
  2328. return cnt;
  2329. }
  2330. #if NET_2_0
  2331. [MonoTODO ("Not implemented")]
  2332. public int ReceiveMessageFrom (byte[] buffer, int offset,
  2333. int size,
  2334. ref SocketFlags socketFlags,
  2335. ref EndPoint remoteEP,
  2336. out IPPacketInformation ipPacketInformation)
  2337. {
  2338. if (disposed && closed)
  2339. throw new ObjectDisposedException (GetType ().ToString ());
  2340. if (buffer == null)
  2341. throw new ArgumentNullException ("buffer");
  2342. if (remoteEP == null)
  2343. throw new ArgumentNullException ("remoteEP");
  2344. if (offset < 0 || offset > buffer.Length)
  2345. throw new ArgumentOutOfRangeException ("offset");
  2346. if (size < 0 || offset + size > buffer.Length)
  2347. throw new ArgumentOutOfRangeException ("size");
  2348. /* FIXME: figure out how we get hold of the
  2349. * IPPacketInformation
  2350. */
  2351. throw new NotImplementedException ();
  2352. }
  2353. #endif
  2354. public int Send (byte [] buf)
  2355. {
  2356. if (disposed && closed)
  2357. throw new ObjectDisposedException (GetType ().ToString ());
  2358. if (buf == null)
  2359. throw new ArgumentNullException ("buf");
  2360. SocketError error;
  2361. int ret = Send_nochecks (buf, 0, buf.Length, SocketFlags.None, out error);
  2362. if (error != SocketError.Success)
  2363. throw new SocketException ((int) error);
  2364. return ret;
  2365. }
  2366. public int Send (byte [] buf, SocketFlags flags)
  2367. {
  2368. if (disposed && closed)
  2369. throw new ObjectDisposedException (GetType ().ToString ());
  2370. if (buf == null)
  2371. throw new ArgumentNullException ("buf");
  2372. SocketError error;
  2373. int ret = Send_nochecks (buf, 0, buf.Length, flags, out error);
  2374. if (error != SocketError.Success)
  2375. throw new SocketException ((int) error);
  2376. return ret;
  2377. }
  2378. public int Send (byte [] buf, int size, SocketFlags flags)
  2379. {
  2380. if (disposed && closed)
  2381. throw new ObjectDisposedException (GetType ().ToString ());
  2382. if (buf == null)
  2383. throw new ArgumentNullException ("buf");
  2384. if (size < 0 || size > buf.Length)
  2385. throw new ArgumentOutOfRangeException ("size");
  2386. SocketError error;
  2387. int ret = Send_nochecks (buf, 0, size, flags, out error);
  2388. if (error != SocketError.Success)
  2389. throw new SocketException ((int) error);
  2390. return ret;
  2391. }
  2392. public int Send (byte [] buf, int offset, int size, SocketFlags flags)
  2393. {
  2394. if (disposed && closed)
  2395. throw new ObjectDisposedException (GetType ().ToString ());
  2396. if (buf == null)
  2397. throw new ArgumentNullException ("buffer");
  2398. if (offset < 0 || offset > buf.Length)
  2399. throw new ArgumentOutOfRangeException ("offset");
  2400. if (size < 0 || offset + size > buf.Length)
  2401. throw new ArgumentOutOfRangeException ("size");
  2402. SocketError error;
  2403. int ret = Send_nochecks (buf, offset, size, flags, out error);
  2404. if (error != SocketError.Success)
  2405. throw new SocketException ((int) error);
  2406. return ret;
  2407. }
  2408. #if NET_2_0
  2409. public int Send (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  2410. {
  2411. if (disposed && closed)
  2412. throw new ObjectDisposedException (GetType ().ToString ());
  2413. if (buf == null)
  2414. throw new ArgumentNullException ("buffer");
  2415. if (offset < 0 || offset > buf.Length)
  2416. throw new ArgumentOutOfRangeException ("offset");
  2417. if (size < 0 || offset + size > buf.Length)
  2418. throw new ArgumentOutOfRangeException ("size");
  2419. return Send_nochecks (buf, offset, size, flags, out error);
  2420. }
  2421. [MonoTODO]
  2422. public int Send (IList<ArraySegment<byte>> buffers)
  2423. {
  2424. /* For these generic IList overloads I need to
  2425. * implement WSASend in the runtime
  2426. */
  2427. throw new NotImplementedException ();
  2428. }
  2429. [MonoTODO]
  2430. public int Send (IList<ArraySegment<byte>> buffers,
  2431. SocketFlags socketFlags)
  2432. {
  2433. throw new NotImplementedException ();
  2434. }
  2435. [CLSCompliant (false)]
  2436. [MonoTODO]
  2437. public int Send (IList<ArraySegment<byte>> buffers,
  2438. SocketFlags socketFlags,
  2439. out SocketError errorCode)
  2440. {
  2441. throw new NotImplementedException ();
  2442. }
  2443. #endif
  2444. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2445. private extern static int Send_internal(IntPtr sock,
  2446. byte[] buf, int offset,
  2447. int count,
  2448. SocketFlags flags,
  2449. out int error);
  2450. int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  2451. {
  2452. if (size == 0) {
  2453. error = SocketError.Success;
  2454. return 0;
  2455. }
  2456. int nativeError;
  2457. int ret = Send_internal (socket, buf, offset, size, flags, out nativeError);
  2458. error = (SocketError)nativeError;
  2459. if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress)
  2460. connected = false;
  2461. else
  2462. connected = true;
  2463. return ret;
  2464. }
  2465. #if NET_2_0
  2466. [MonoTODO ("Not implemented")]
  2467. public void SendFile (string fileName)
  2468. {
  2469. if (disposed && closed)
  2470. throw new ObjectDisposedException (GetType ().ToString ());
  2471. if (!connected)
  2472. throw new NotSupportedException ();
  2473. if (!blocking)
  2474. throw new InvalidOperationException ();
  2475. if (!File.Exists (fileName))
  2476. throw new FileNotFoundException ();
  2477. /* FIXME: Implement TransmitFile */
  2478. throw new NotImplementedException ();
  2479. }
  2480. [MonoTODO ("Not implemented")]
  2481. public void SendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
  2482. {
  2483. if (disposed && closed)
  2484. throw new ObjectDisposedException (GetType ().ToString ());
  2485. if (!connected)
  2486. throw new NotSupportedException ();
  2487. if (!blocking)
  2488. throw new InvalidOperationException ();
  2489. if (!File.Exists (fileName))
  2490. throw new FileNotFoundException ();
  2491. /* FIXME: Implement TransmitFile */
  2492. throw new NotImplementedException ();
  2493. }
  2494. #endif
  2495. public int SendTo (byte [] buffer, EndPoint remote_end)
  2496. {
  2497. if (disposed && closed)
  2498. throw new ObjectDisposedException (GetType ().ToString ());
  2499. if (buffer == null)
  2500. throw new ArgumentNullException ("buffer");
  2501. if (remote_end == null)
  2502. throw new ArgumentNullException ("remote_end");
  2503. return SendTo_nochecks (buffer, 0, buffer.Length, SocketFlags.None, remote_end);
  2504. }
  2505. public int SendTo (byte [] buffer, SocketFlags flags, EndPoint remote_end)
  2506. {
  2507. if (disposed && closed)
  2508. throw new ObjectDisposedException (GetType ().ToString ());
  2509. if (buffer == null)
  2510. throw new ArgumentNullException ("buffer");
  2511. if (remote_end == null)
  2512. throw new ArgumentNullException ("remote_end");
  2513. return SendTo_nochecks (buffer, 0, buffer.Length, flags, remote_end);
  2514. }
  2515. public int SendTo (byte [] buffer, int size, SocketFlags flags, EndPoint remote_end)
  2516. {
  2517. if (disposed && closed)
  2518. throw new ObjectDisposedException (GetType ().ToString ());
  2519. if (buffer == null)
  2520. throw new ArgumentNullException ("buffer");
  2521. if (remote_end == null)
  2522. throw new ArgumentNullException ("remote_end");
  2523. if (size < 0 || size > buffer.Length)
  2524. throw new ArgumentOutOfRangeException ("size");
  2525. return SendTo_nochecks (buffer, 0, size, flags, remote_end);
  2526. }
  2527. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2528. private extern static int SendTo_internal(IntPtr sock,
  2529. byte[] buffer,
  2530. int offset,
  2531. int count,
  2532. SocketFlags flags,
  2533. SocketAddress sa,
  2534. out int error);
  2535. public int SendTo (byte [] buffer, int offset, int size, SocketFlags flags,
  2536. EndPoint remote_end)
  2537. {
  2538. if (disposed && closed)
  2539. throw new ObjectDisposedException (GetType ().ToString ());
  2540. if (buffer == null)
  2541. throw new ArgumentNullException ("buffer");
  2542. if (remote_end == null)
  2543. throw new ArgumentNullException("remote_end");
  2544. if (offset < 0 || offset > buffer.Length)
  2545. throw new ArgumentOutOfRangeException ("offset");
  2546. if (size < 0 || offset + size > buffer.Length)
  2547. throw new ArgumentOutOfRangeException ("size");
  2548. return SendTo_nochecks (buffer, offset, size, flags, remote_end);
  2549. }
  2550. int SendTo_nochecks (byte [] buffer, int offset, int size, SocketFlags flags,
  2551. EndPoint remote_end)
  2552. {
  2553. SocketAddress sockaddr = remote_end.Serialize ();
  2554. int ret, error;
  2555. ret = SendTo_internal (socket, buffer, offset, size, flags, sockaddr, out error);
  2556. SocketError err = (SocketError) error;
  2557. if (err != 0) {
  2558. if (err != SocketError.WouldBlock && err != SocketError.InProgress)
  2559. connected = false;
  2560. throw new SocketException (error);
  2561. }
  2562. connected = true;
  2563. #if NET_2_0
  2564. isbound = true;
  2565. #endif
  2566. seed_endpoint = remote_end;
  2567. return ret;
  2568. }
  2569. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2570. private extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level,
  2571. SocketOptionName name, object obj_val,
  2572. byte [] byte_val, int int_val,
  2573. out int error);
  2574. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, byte[] opt_value)
  2575. {
  2576. if (disposed && closed)
  2577. throw new ObjectDisposedException (GetType ().ToString ());
  2578. int error;
  2579. SetSocketOption_internal(socket, level, name, null,
  2580. opt_value, 0, out error);
  2581. if (error != 0)
  2582. throw new SocketException (error);
  2583. }
  2584. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, int opt_value)
  2585. {
  2586. if (disposed && closed)
  2587. throw new ObjectDisposedException (GetType ().ToString ());
  2588. int error;
  2589. SetSocketOption_internal(socket, level, name, null,
  2590. null, opt_value, out error);
  2591. if (error != 0)
  2592. throw new SocketException (error);
  2593. }
  2594. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, object opt_value)
  2595. {
  2596. if (disposed && closed)
  2597. throw new ObjectDisposedException (GetType ().ToString ());
  2598. if (opt_value == null)
  2599. throw new ArgumentNullException("opt_value");
  2600. int error;
  2601. /* From MS documentation on SetSocketOption: "For an
  2602. * option with a Boolean data type, specify a nonzero
  2603. * value to enable the option, and a zero value to
  2604. * disable the option."
  2605. * Booleans are only handled in 2.0
  2606. */
  2607. if (opt_value is System.Boolean) {
  2608. #if NET_2_0
  2609. bool bool_val = (bool) opt_value;
  2610. int int_val = (bool_val) ? 1 : 0;
  2611. SetSocketOption_internal (socket, level, name, null, null, int_val, out error);
  2612. #else
  2613. throw new ArgumentException ("Use an integer 1 (true) or 0 (false) instead of a boolean.", "opt_value");
  2614. #endif
  2615. } else {
  2616. SetSocketOption_internal (socket, level, name, opt_value, null, 0, out error);
  2617. }
  2618. if (error != 0)
  2619. throw new SocketException (error);
  2620. }
  2621. #if NET_2_0
  2622. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, bool optionValue)
  2623. {
  2624. if (disposed && closed)
  2625. throw new ObjectDisposedException (GetType ().ToString ());
  2626. int error;
  2627. int int_val = (optionValue) ? 1 : 0;
  2628. SetSocketOption_internal (socket, level, name, null, null, int_val, out error);
  2629. if (error != 0)
  2630. throw new SocketException (error);
  2631. }
  2632. #endif
  2633. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2634. private extern static void Shutdown_internal(IntPtr socket, SocketShutdown how, out int error);
  2635. public void Shutdown (SocketShutdown how)
  2636. {
  2637. if (disposed && closed)
  2638. throw new ObjectDisposedException (GetType ().ToString ());
  2639. int error;
  2640. Shutdown_internal (socket, how, out error);
  2641. if (error != 0)
  2642. throw new SocketException (error);
  2643. }
  2644. #if ONLY_1_1
  2645. public override int GetHashCode ()
  2646. {
  2647. // LAMESPEC:
  2648. // The socket is not suitable to serve as a hash code,
  2649. // because it will change during its lifetime, but
  2650. // this is how MS.NET 1.1 implemented this method.
  2651. return (int) socket;
  2652. }
  2653. #endif
  2654. protected virtual void Dispose (bool explicitDisposing)
  2655. {
  2656. if (disposed)
  2657. return;
  2658. disposed = true;
  2659. connected = false;
  2660. if ((int) socket != -1) {
  2661. int error;
  2662. closed = true;
  2663. IntPtr x = socket;
  2664. socket = (IntPtr) (-1);
  2665. Close_internal (x, out error);
  2666. if (blocking_thread != null) {
  2667. blocking_thread.Abort ();
  2668. blocking_thread = null;
  2669. }
  2670. if (error != 0)
  2671. throw new SocketException (error);
  2672. }
  2673. }
  2674. void IDisposable.Dispose ()
  2675. {
  2676. Dispose (true);
  2677. GC.SuppressFinalize (this);
  2678. }
  2679. ~Socket () {
  2680. Dispose (false);
  2681. }
  2682. }
  2683. }