Socket.cs 91 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456
  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. internal 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. internal set { connected = value; }
  694. }
  695. #if NET_2_0
  696. public bool DontFragment {
  697. get {
  698. if (disposed && closed) {
  699. throw new ObjectDisposedException (GetType ().ToString ());
  700. }
  701. bool dontfragment;
  702. if (address_family == AddressFamily.InterNetwork) {
  703. dontfragment = (int)(GetSocketOption (SocketOptionLevel.IP, SocketOptionName.DontFragment)) != 0;
  704. } else if (address_family == AddressFamily.InterNetworkV6) {
  705. dontfragment = (int)(GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DontFragment)) != 0;
  706. } else {
  707. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  708. }
  709. return(dontfragment);
  710. }
  711. set {
  712. if (disposed && closed) {
  713. throw new ObjectDisposedException (GetType ().ToString ());
  714. }
  715. if (address_family == AddressFamily.InterNetwork) {
  716. SetSocketOption (SocketOptionLevel.IP, SocketOptionName.DontFragment, value?1:0);
  717. } else if (address_family == AddressFamily.InterNetworkV6) {
  718. SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.DontFragment, value?1:0);
  719. } else {
  720. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  721. }
  722. }
  723. }
  724. public bool EnableBroadcast {
  725. get {
  726. if (disposed && closed) {
  727. throw new ObjectDisposedException (GetType ().ToString ());
  728. }
  729. if (protocol_type != ProtocolType.Udp) {
  730. throw new SocketException ((int)SocketError.ProtocolOption);
  731. }
  732. return((int)(GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast)) != 0);
  733. }
  734. set {
  735. if (disposed && closed) {
  736. throw new ObjectDisposedException (GetType ().ToString ());
  737. }
  738. if (protocol_type != ProtocolType.Udp) {
  739. throw new SocketException ((int)SocketError.ProtocolOption);
  740. }
  741. SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Broadcast, value?1:0);
  742. }
  743. }
  744. public bool ExclusiveAddressUse {
  745. get {
  746. if (disposed && closed) {
  747. throw new ObjectDisposedException (GetType ().ToString ());
  748. }
  749. return((int)(GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse)) != 0);
  750. }
  751. set {
  752. if (disposed && closed) {
  753. throw new ObjectDisposedException (GetType ().ToString ());
  754. }
  755. if (isbound) {
  756. throw new InvalidOperationException ("Bind has already been called for this socket");
  757. }
  758. SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, value?1:0);
  759. }
  760. }
  761. public bool IsBound {
  762. get {
  763. return(isbound);
  764. }
  765. }
  766. public LingerOption LingerState {
  767. get {
  768. if (disposed && closed) {
  769. throw new ObjectDisposedException (GetType ().ToString ());
  770. }
  771. return((LingerOption)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Linger));
  772. }
  773. set {
  774. if (disposed && closed) {
  775. throw new ObjectDisposedException (GetType ().ToString ());
  776. }
  777. SetSocketOption (SocketOptionLevel.Socket,
  778. SocketOptionName.Linger,
  779. value);
  780. }
  781. }
  782. public bool MulticastLoopback {
  783. get {
  784. if (disposed && closed) {
  785. throw new ObjectDisposedException (GetType ().ToString ());
  786. }
  787. /* Even though this option can be set
  788. * for TCP sockets on Linux, throw
  789. * this exception anyway to be
  790. * compatible (the MSDN docs say
  791. * "Setting this property on a
  792. * Transmission Control Protocol (TCP)
  793. * socket will have no effect." but
  794. * the MS runtime throws the
  795. * exception...)
  796. */
  797. if (protocol_type == ProtocolType.Tcp) {
  798. throw new SocketException ((int)SocketError.ProtocolOption);
  799. }
  800. bool multicastloopback;
  801. if (address_family == AddressFamily.InterNetwork) {
  802. multicastloopback = (int)(GetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback)) != 0;
  803. } else if (address_family == AddressFamily.InterNetworkV6) {
  804. multicastloopback = (int)(GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback)) != 0;
  805. } else {
  806. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  807. }
  808. return(multicastloopback);
  809. }
  810. set {
  811. if (disposed && closed) {
  812. throw new ObjectDisposedException (GetType ().ToString ());
  813. }
  814. /* Even though this option can be set
  815. * for TCP sockets on Linux, throw
  816. * this exception anyway to be
  817. * compatible (the MSDN docs say
  818. * "Setting this property on a
  819. * Transmission Control Protocol (TCP)
  820. * socket will have no effect." but
  821. * the MS runtime throws the
  822. * exception...)
  823. */
  824. if (protocol_type == ProtocolType.Tcp) {
  825. throw new SocketException ((int)SocketError.ProtocolOption);
  826. }
  827. if (address_family == AddressFamily.InterNetwork) {
  828. SetSocketOption (SocketOptionLevel.IP, SocketOptionName.MulticastLoopback, value?1:0);
  829. } else if (address_family == AddressFamily.InterNetworkV6) {
  830. SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.MulticastLoopback, value?1:0);
  831. } else {
  832. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  833. }
  834. }
  835. }
  836. public static bool OSSupportsIPv6 {
  837. get {
  838. NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces ();
  839. foreach(NetworkInterface adapter in nics) {
  840. if (adapter.Supports (NetworkInterfaceComponent.IPv6) == true) {
  841. return(true);
  842. } else {
  843. continue;
  844. }
  845. }
  846. return(false);
  847. }
  848. }
  849. public int ReceiveBufferSize {
  850. get {
  851. if (disposed && closed) {
  852. throw new ObjectDisposedException (GetType ().ToString ());
  853. }
  854. return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer));
  855. }
  856. set {
  857. if (disposed && closed) {
  858. throw new ObjectDisposedException (GetType ().ToString ());
  859. }
  860. if (value < 0) {
  861. throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
  862. }
  863. SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, value);
  864. }
  865. }
  866. public int SendBufferSize {
  867. get {
  868. if (disposed && closed) {
  869. throw new ObjectDisposedException (GetType ().ToString ());
  870. }
  871. return((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendBuffer));
  872. }
  873. set {
  874. if (disposed && closed) {
  875. throw new ObjectDisposedException (GetType ().ToString ());
  876. }
  877. if (value < 0) {
  878. throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than zero");
  879. }
  880. SetSocketOption (SocketOptionLevel.Socket,
  881. SocketOptionName.SendBuffer,
  882. value);
  883. }
  884. }
  885. public short Ttl {
  886. get {
  887. if (disposed && closed) {
  888. throw new ObjectDisposedException (GetType ().ToString ());
  889. }
  890. short ttl_val;
  891. if (address_family == AddressFamily.InterNetwork) {
  892. ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive));
  893. } else if (address_family == AddressFamily.InterNetworkV6) {
  894. ttl_val = (short)((int)GetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit));
  895. } else {
  896. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  897. }
  898. return(ttl_val);
  899. }
  900. set {
  901. if (disposed && closed) {
  902. throw new ObjectDisposedException (GetType ().ToString ());
  903. }
  904. if (address_family == AddressFamily.InterNetwork) {
  905. SetSocketOption (SocketOptionLevel.IP, SocketOptionName.IpTimeToLive, value);
  906. } else if (address_family == AddressFamily.InterNetworkV6) {
  907. SetSocketOption (SocketOptionLevel.IPv6, SocketOptionName.HopLimit, value);
  908. } else {
  909. throw new NotSupportedException ("This property is only valid for InterNetwork and InterNetworkV6 sockets");
  910. }
  911. }
  912. }
  913. [MonoTODO ("This doesn't do anything on Mono yet")]
  914. public bool UseOnlyOverlappedIO {
  915. get {
  916. return(useoverlappedIO);
  917. }
  918. set {
  919. useoverlappedIO = value;
  920. }
  921. }
  922. #endif
  923. public IntPtr Handle {
  924. get {
  925. return(socket);
  926. }
  927. }
  928. #if !TARGET_JVM
  929. // Returns the local endpoint details in addr and port
  930. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  931. private extern static SocketAddress LocalEndPoint_internal(IntPtr socket, out int error);
  932. #endif
  933. // Wish: support non-IP endpoints.
  934. public EndPoint LocalEndPoint {
  935. get {
  936. if (disposed && closed)
  937. throw new ObjectDisposedException (GetType ().ToString ());
  938. /*
  939. * If the seed EndPoint is null, Connect, Bind,
  940. * etc has not yet been called. MS returns null
  941. * in this case.
  942. */
  943. if (seed_endpoint == null)
  944. return null;
  945. SocketAddress sa;
  946. int error;
  947. sa=LocalEndPoint_internal(socket, out error);
  948. if (error != 0)
  949. throw new SocketException (error);
  950. return seed_endpoint.Create (sa);
  951. }
  952. }
  953. public ProtocolType ProtocolType {
  954. get {
  955. return(protocol_type);
  956. }
  957. }
  958. // Returns the remote endpoint details in addr and port
  959. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  960. private extern static SocketAddress RemoteEndPoint_internal(IntPtr socket, out int error);
  961. public EndPoint RemoteEndPoint {
  962. get {
  963. if (disposed && closed)
  964. throw new ObjectDisposedException (GetType ().ToString ());
  965. /*
  966. * If the seed EndPoint is null, Connect, Bind,
  967. * etc has not yet been called. MS returns null
  968. * in this case.
  969. */
  970. if (seed_endpoint == null)
  971. return null;
  972. SocketAddress sa;
  973. int error;
  974. sa=RemoteEndPoint_internal(socket, out error);
  975. if (error != 0)
  976. throw new SocketException (error);
  977. return seed_endpoint.Create (sa);
  978. }
  979. }
  980. public SocketType SocketType {
  981. get {
  982. return(socket_type);
  983. }
  984. }
  985. public static bool SupportsIPv4 {
  986. get {
  987. CheckProtocolSupport();
  988. return ipv4Supported == 1;
  989. }
  990. }
  991. #if NET_2_0
  992. [ObsoleteAttribute ("Use OSSupportsIPv6 instead")]
  993. #endif
  994. public static bool SupportsIPv6 {
  995. get {
  996. CheckProtocolSupport();
  997. return ipv6Supported == 1;
  998. }
  999. }
  1000. #if NET_2_0
  1001. public int SendTimeout {
  1002. get {
  1003. if (disposed && closed)
  1004. throw new ObjectDisposedException (GetType ().ToString ());
  1005. return (int)GetSocketOption(
  1006. SocketOptionLevel.Socket,
  1007. SocketOptionName.SendTimeout);
  1008. }
  1009. set {
  1010. if (disposed && closed)
  1011. throw new ObjectDisposedException (GetType ().ToString ());
  1012. if (value < -1)
  1013. throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than -1");
  1014. /* According to the MSDN docs we
  1015. * should adjust values between 1 and
  1016. * 499 to 500, but the MS runtime
  1017. * doesn't do this.
  1018. */
  1019. if (value == -1)
  1020. value = 0;
  1021. SetSocketOption(
  1022. SocketOptionLevel.Socket,
  1023. SocketOptionName.SendTimeout, value);
  1024. }
  1025. }
  1026. public int ReceiveTimeout {
  1027. get {
  1028. if (disposed && closed)
  1029. throw new ObjectDisposedException (GetType ().ToString ());
  1030. return (int)GetSocketOption(
  1031. SocketOptionLevel.Socket,
  1032. SocketOptionName.ReceiveTimeout);
  1033. }
  1034. set {
  1035. if (disposed && closed)
  1036. throw new ObjectDisposedException (GetType ().ToString ());
  1037. if (value < -1)
  1038. throw new ArgumentOutOfRangeException ("value", "The value specified for a set operation is less than -1");
  1039. if (value == -1) {
  1040. value = 0;
  1041. }
  1042. SetSocketOption(
  1043. SocketOptionLevel.Socket,
  1044. SocketOptionName.ReceiveTimeout, value);
  1045. }
  1046. }
  1047. public bool NoDelay {
  1048. get {
  1049. if (disposed && closed)
  1050. throw new ObjectDisposedException (GetType ().ToString ());
  1051. if (protocol_type == ProtocolType.Udp)
  1052. throw new SocketException ((int)SocketError.ProtocolOption);
  1053. return (int)(GetSocketOption (
  1054. SocketOptionLevel.Tcp,
  1055. SocketOptionName.NoDelay)) != 0;
  1056. }
  1057. set {
  1058. if (disposed && closed)
  1059. throw new ObjectDisposedException (GetType ().ToString ());
  1060. if (protocol_type == ProtocolType.Udp)
  1061. throw new SocketException ((int)SocketError.ProtocolOption);
  1062. SetSocketOption (
  1063. SocketOptionLevel.Tcp,
  1064. SocketOptionName.NoDelay, value ? 1 : 0);
  1065. }
  1066. }
  1067. #endif
  1068. internal static void CheckProtocolSupport ()
  1069. {
  1070. if(ipv4Supported == -1) {
  1071. try {
  1072. Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  1073. tmp.Close();
  1074. ipv4Supported = 1;
  1075. } catch {
  1076. ipv4Supported = 0;
  1077. }
  1078. }
  1079. if (ipv6Supported == -1) {
  1080. #if !NET_2_1
  1081. #if NET_2_0 && CONFIGURATION_DEP
  1082. SettingsSection config;
  1083. config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
  1084. if (config != null)
  1085. ipv6Supported = config.Ipv6.Enabled ? -1 : 0;
  1086. #else
  1087. NetConfig config = (NetConfig)System.Configuration.ConfigurationSettings.GetConfig("system.net/settings");
  1088. if (config != null)
  1089. ipv6Supported = config.ipv6Enabled ? -1 : 0;
  1090. #endif
  1091. #endif
  1092. if (ipv6Supported != 0) {
  1093. try {
  1094. Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
  1095. tmp.Close();
  1096. ipv6Supported = 1;
  1097. } catch { }
  1098. }
  1099. }
  1100. }
  1101. #if NET_2_0
  1102. public bool AcceptAsync (SocketAsyncEventArgs e)
  1103. {
  1104. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1105. if (disposed && closed)
  1106. throw new ObjectDisposedException (GetType ().ToString ());
  1107. if (!IsBound)
  1108. throw new InvalidOperationException ("You must call the Bind method before performing this operation.");
  1109. if (!islistening)
  1110. throw new InvalidOperationException ("You must call the Listen method before performing this operation.");
  1111. if (e.BufferList != null)
  1112. throw new ArgumentException ("Multiple buffers cannot be used with this method.");
  1113. if (e.Count < 0)
  1114. throw new ArgumentOutOfRangeException ("e.Count");
  1115. Socket acceptSocket = e.AcceptSocket;
  1116. if (acceptSocket != null) {
  1117. if (acceptSocket.IsBound || acceptSocket.Connected)
  1118. throw new InvalidOperationException ("AcceptSocket: The socket must not be bound or connected.");
  1119. } else
  1120. e.AcceptSocket = new Socket (AddressFamily, SocketType, ProtocolType);
  1121. try {
  1122. e.DoOperation (SocketAsyncOperation.Accept, this);
  1123. } catch {
  1124. ((IDisposable)e).Dispose ();
  1125. throw;
  1126. }
  1127. // We always return true for now
  1128. return true;
  1129. }
  1130. #endif
  1131. // Creates a new system socket, returning the handle
  1132. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1133. private extern static IntPtr Accept_internal(IntPtr sock, out int error);
  1134. Thread blocking_thread;
  1135. public Socket Accept() {
  1136. if (disposed && closed)
  1137. throw new ObjectDisposedException (GetType ().ToString ());
  1138. int error = 0;
  1139. IntPtr sock = (IntPtr) (-1);
  1140. blocking_thread = Thread.CurrentThread;
  1141. try {
  1142. sock = Accept_internal(socket, out error);
  1143. } catch (ThreadAbortException) {
  1144. if (disposed) {
  1145. Thread.ResetAbort ();
  1146. error = (int) SocketError.Interrupted;
  1147. }
  1148. } finally {
  1149. blocking_thread = null;
  1150. }
  1151. if (error != 0)
  1152. throw new SocketException (error);
  1153. Socket accepted = new Socket(this.AddressFamily, this.SocketType,
  1154. this.ProtocolType, sock);
  1155. accepted.seed_endpoint = this.seed_endpoint;
  1156. accepted.Blocking = this.Blocking;
  1157. return(accepted);
  1158. }
  1159. internal void Accept (Socket acceptSocket)
  1160. {
  1161. if (disposed && closed)
  1162. throw new ObjectDisposedException (GetType ().ToString ());
  1163. int error = 0;
  1164. IntPtr sock = (IntPtr)(-1);
  1165. blocking_thread = Thread.CurrentThread;
  1166. try {
  1167. sock = Accept_internal (socket, out error);
  1168. } catch (ThreadAbortException) {
  1169. if (disposed) {
  1170. Thread.ResetAbort ();
  1171. error = (int)SocketError.Interrupted;
  1172. }
  1173. } finally {
  1174. blocking_thread = null;
  1175. }
  1176. if (error != 0)
  1177. throw new SocketException (error);
  1178. acceptSocket.address_family = this.AddressFamily;
  1179. acceptSocket.socket_type = this.SocketType;
  1180. acceptSocket.protocol_type = this.ProtocolType;
  1181. acceptSocket.socket = sock;
  1182. acceptSocket.connected = true;
  1183. acceptSocket.seed_endpoint = this.seed_endpoint;
  1184. acceptSocket.Blocking = this.Blocking;
  1185. /* FIXME: figure out what if anything else
  1186. * needs to be reset
  1187. */
  1188. }
  1189. public IAsyncResult BeginAccept(AsyncCallback callback,
  1190. object state)
  1191. {
  1192. if (disposed && closed)
  1193. throw new ObjectDisposedException (GetType ().ToString ());
  1194. #if NET_2_0
  1195. /* FIXME: check the 1.1 docs for this too */
  1196. if (!isbound || !islistening)
  1197. throw new InvalidOperationException ();
  1198. #endif
  1199. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Accept);
  1200. Worker worker = new Worker (req);
  1201. SocketAsyncCall sac = new SocketAsyncCall (worker.Accept);
  1202. sac.BeginInvoke (null, req);
  1203. return(req);
  1204. }
  1205. #if NET_2_0
  1206. public IAsyncResult BeginAccept (int receiveSize,
  1207. AsyncCallback callback,
  1208. object state)
  1209. {
  1210. if (disposed && closed)
  1211. throw new ObjectDisposedException (GetType ().ToString ());
  1212. if (receiveSize < 0)
  1213. throw new ArgumentOutOfRangeException ("receiveSize", "receiveSize is less than zero");
  1214. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.AcceptReceive);
  1215. Worker worker = new Worker (req);
  1216. SocketAsyncCall sac = new SocketAsyncCall (worker.AcceptReceive);
  1217. req.Buffer = new byte[receiveSize];
  1218. req.Offset = 0;
  1219. req.Size = receiveSize;
  1220. req.SockFlags = SocketFlags.None;
  1221. sac.BeginInvoke (null, req);
  1222. return(req);
  1223. }
  1224. public IAsyncResult BeginAccept (Socket acceptSocket,
  1225. int receiveSize,
  1226. AsyncCallback callback,
  1227. object state)
  1228. {
  1229. if (disposed && closed)
  1230. throw new ObjectDisposedException (GetType ().ToString ());
  1231. if (receiveSize < 0)
  1232. throw new ArgumentOutOfRangeException ("receiveSize", "receiveSize is less than zero");
  1233. if (acceptSocket != null) {
  1234. if (acceptSocket.disposed && acceptSocket.closed)
  1235. throw new ObjectDisposedException (acceptSocket.GetType ().ToString ());
  1236. if (acceptSocket.IsBound)
  1237. throw new InvalidOperationException ();
  1238. /* For some reason the MS runtime
  1239. * barfs if the new socket is not TCP,
  1240. * even though it's just about to blow
  1241. * away all those parameters
  1242. */
  1243. if (acceptSocket.ProtocolType != ProtocolType.Tcp)
  1244. throw new SocketException ((int)SocketError.InvalidArgument);
  1245. }
  1246. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.AcceptReceive);
  1247. Worker worker = new Worker (req);
  1248. SocketAsyncCall sac = new SocketAsyncCall (worker.AcceptReceive);
  1249. req.Buffer = new byte[receiveSize];
  1250. req.Offset = 0;
  1251. req.Size = receiveSize;
  1252. req.SockFlags = SocketFlags.None;
  1253. req.AcceptSocket = acceptSocket;
  1254. sac.BeginInvoke (null, req);
  1255. return(req);
  1256. }
  1257. #endif
  1258. public IAsyncResult BeginConnect(EndPoint end_point,
  1259. AsyncCallback callback,
  1260. object state) {
  1261. if (disposed && closed)
  1262. throw new ObjectDisposedException (GetType ().ToString ());
  1263. if (end_point == null)
  1264. throw new ArgumentNullException ("end_point");
  1265. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
  1266. req.EndPoint = end_point;
  1267. // Bug #75154: Connect() should not succeed for .Any addresses.
  1268. if (end_point is IPEndPoint) {
  1269. IPEndPoint ep = (IPEndPoint) end_point;
  1270. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
  1271. req.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
  1272. return req;
  1273. }
  1274. }
  1275. int error = 0;
  1276. if (!blocking) {
  1277. SocketAddress serial = end_point.Serialize ();
  1278. Connect_internal (socket, serial, out error);
  1279. if (error == 0) {
  1280. // succeeded synch
  1281. connected = true;
  1282. req.Complete (true);
  1283. } else if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
  1284. // error synch
  1285. connected = false;
  1286. req.Complete (new SocketException (error), true);
  1287. }
  1288. }
  1289. if (blocking || error == (int) SocketError.InProgress || error == (int) SocketError.WouldBlock) {
  1290. // continue asynch
  1291. connected = false;
  1292. Worker worker = new Worker (req);
  1293. SocketAsyncCall sac = new SocketAsyncCall (worker.Connect);
  1294. sac.BeginInvoke (null, req);
  1295. }
  1296. return(req);
  1297. }
  1298. #if NET_2_0
  1299. public IAsyncResult BeginConnect (IPAddress address, int port,
  1300. AsyncCallback callback,
  1301. object state)
  1302. {
  1303. if (disposed && closed)
  1304. throw new ObjectDisposedException (GetType ().ToString ());
  1305. if (address == null)
  1306. throw new ArgumentNullException ("address");
  1307. if (address.ToString ().Length == 0)
  1308. throw new ArgumentException ("The length of the IP address is zero");
  1309. if (islistening)
  1310. throw new InvalidOperationException ();
  1311. IPEndPoint iep = new IPEndPoint (address, port);
  1312. return(BeginConnect (iep, callback, state));
  1313. }
  1314. public IAsyncResult BeginConnect (IPAddress[] addresses,
  1315. int port,
  1316. AsyncCallback callback,
  1317. object state)
  1318. {
  1319. if (disposed && closed)
  1320. throw new ObjectDisposedException (GetType ().ToString ());
  1321. if (addresses == null)
  1322. throw new ArgumentNullException ("addresses");
  1323. if (this.AddressFamily != AddressFamily.InterNetwork &&
  1324. this.AddressFamily != AddressFamily.InterNetworkV6)
  1325. throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
  1326. if (islistening)
  1327. throw new InvalidOperationException ();
  1328. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
  1329. req.Addresses = addresses;
  1330. req.Port = port;
  1331. connected = false;
  1332. Worker worker = new Worker (req);
  1333. SocketAsyncCall sac = new SocketAsyncCall (worker.Connect);
  1334. sac.BeginInvoke (null, req);
  1335. return(req);
  1336. }
  1337. public IAsyncResult BeginConnect (string host, int port,
  1338. AsyncCallback callback,
  1339. object state)
  1340. {
  1341. if (disposed && closed)
  1342. throw new ObjectDisposedException (GetType ().ToString ());
  1343. if (host == null)
  1344. throw new ArgumentNullException ("host");
  1345. if (address_family != AddressFamily.InterNetwork &&
  1346. address_family != AddressFamily.InterNetworkV6)
  1347. throw new NotSupportedException ("This method is valid only for sockets in the InterNetwork and InterNetworkV6 families");
  1348. if (islistening)
  1349. throw new InvalidOperationException ();
  1350. IPHostEntry hostent = Dns.GetHostEntry (host);
  1351. return (BeginConnect (hostent.AddressList, port, callback, state));
  1352. }
  1353. public IAsyncResult BeginDisconnect (bool reuseSocket,
  1354. AsyncCallback callback,
  1355. object state)
  1356. {
  1357. if (disposed && closed)
  1358. throw new ObjectDisposedException (GetType ().ToString ());
  1359. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Disconnect);
  1360. req.ReuseSocket = reuseSocket;
  1361. Worker worker = new Worker (req);
  1362. SocketAsyncCall sac = new SocketAsyncCall (worker.Disconnect);
  1363. sac.BeginInvoke (null, req);
  1364. return(req);
  1365. }
  1366. #endif
  1367. public IAsyncResult BeginReceive(byte[] buffer, int offset,
  1368. int size,
  1369. SocketFlags socket_flags,
  1370. AsyncCallback callback,
  1371. object state) {
  1372. if (disposed && closed)
  1373. throw new ObjectDisposedException (GetType ().ToString ());
  1374. if (buffer == null)
  1375. throw new ArgumentNullException ("buffer");
  1376. if (offset < 0 || offset > buffer.Length)
  1377. throw new ArgumentOutOfRangeException ("offset");
  1378. if (size < 0 || offset + size > buffer.Length)
  1379. throw new ArgumentOutOfRangeException ("size");
  1380. SocketAsyncResult req;
  1381. lock (readQ) {
  1382. req = new SocketAsyncResult (this, state, callback, SocketOperation.Receive);
  1383. req.Buffer = buffer;
  1384. req.Offset = offset;
  1385. req.Size = size;
  1386. req.SockFlags = socket_flags;
  1387. readQ.Enqueue (req);
  1388. if (readQ.Count == 1) {
  1389. Worker worker = new Worker (req);
  1390. SocketAsyncCall sac = new SocketAsyncCall (worker.Receive);
  1391. sac.BeginInvoke (null, req);
  1392. }
  1393. }
  1394. return req;
  1395. }
  1396. #if NET_2_0
  1397. public IAsyncResult BeginReceive (byte[] buffer, int offset,
  1398. int size, SocketFlags flags,
  1399. out SocketError error,
  1400. AsyncCallback callback,
  1401. object state)
  1402. {
  1403. /* As far as I can tell from the docs and from
  1404. * experimentation, a pointer to the
  1405. * SocketError parameter is not supposed to be
  1406. * saved for the async parts. And as we don't
  1407. * set any socket errors in the setup code, we
  1408. * just have to set it to Success.
  1409. */
  1410. error = SocketError.Success;
  1411. return (BeginReceive (buffer, offset, size, flags, callback, state));
  1412. }
  1413. [CLSCompliant (false)]
  1414. public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers,
  1415. SocketFlags socketFlags,
  1416. AsyncCallback callback,
  1417. object state)
  1418. {
  1419. if (disposed && closed)
  1420. throw new ObjectDisposedException (GetType ().ToString ());
  1421. if (buffers == null)
  1422. throw new ArgumentNullException ("buffers");
  1423. SocketAsyncResult req;
  1424. lock(readQ) {
  1425. req = new SocketAsyncResult (this, state, callback, SocketOperation.Receive);
  1426. req.Buffers = buffers;
  1427. req.SockFlags = socketFlags;
  1428. readQ.Enqueue (req);
  1429. if (readQ.Count == 1) {
  1430. Worker worker = new Worker (req);
  1431. SocketAsyncCall sac = new SocketAsyncCall (worker.Receive);
  1432. sac.BeginInvoke (null, req);
  1433. }
  1434. }
  1435. return(req);
  1436. }
  1437. [CLSCompliant (false)]
  1438. public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers,
  1439. SocketFlags socketFlags,
  1440. out SocketError errorCode,
  1441. AsyncCallback callback,
  1442. object state)
  1443. {
  1444. /* I assume the same SocketError semantics as
  1445. * above
  1446. */
  1447. errorCode = SocketError.Success;
  1448. return (BeginReceive (buffers, socketFlags, callback, state));
  1449. }
  1450. #endif
  1451. public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset,
  1452. int size,
  1453. SocketFlags socket_flags,
  1454. ref EndPoint remote_end,
  1455. AsyncCallback callback,
  1456. object state) {
  1457. if (disposed && closed)
  1458. throw new ObjectDisposedException (GetType ().ToString ());
  1459. if (buffer == null)
  1460. throw new ArgumentNullException ("buffer");
  1461. if (offset < 0)
  1462. throw new ArgumentOutOfRangeException ("offset", "offset must be >= 0");
  1463. if (size < 0)
  1464. throw new ArgumentOutOfRangeException ("size", "size must be >= 0");
  1465. if (offset + size > buffer.Length)
  1466. throw new ArgumentOutOfRangeException ("offset, size", "offset + size exceeds the buffer length");
  1467. SocketAsyncResult req;
  1468. lock (readQ) {
  1469. req = new SocketAsyncResult (this, state, callback, SocketOperation.ReceiveFrom);
  1470. req.Buffer = buffer;
  1471. req.Offset = offset;
  1472. req.Size = size;
  1473. req.SockFlags = socket_flags;
  1474. req.EndPoint = remote_end;
  1475. readQ.Enqueue (req);
  1476. if (readQ.Count == 1) {
  1477. Worker worker = new Worker (req);
  1478. SocketAsyncCall sac = new SocketAsyncCall (worker.ReceiveFrom);
  1479. sac.BeginInvoke (null, req);
  1480. }
  1481. }
  1482. return req;
  1483. }
  1484. #if NET_2_0
  1485. [MonoTODO]
  1486. public IAsyncResult BeginReceiveMessageFrom (
  1487. byte[] buffer, int offset, int size,
  1488. SocketFlags socketFlags, ref EndPoint remoteEP,
  1489. AsyncCallback callback, object state)
  1490. {
  1491. if (disposed && closed)
  1492. throw new ObjectDisposedException (GetType ().ToString ());
  1493. if (buffer == null)
  1494. throw new ArgumentNullException ("buffer");
  1495. if (remoteEP == null)
  1496. throw new ArgumentNullException ("remoteEP");
  1497. if (offset < 0 || offset > buffer.Length)
  1498. throw new ArgumentOutOfRangeException ("offset");
  1499. if (size < 0 || offset + size > buffer.Length)
  1500. throw new ArgumentOutOfRangeException ("size");
  1501. throw new NotImplementedException ();
  1502. }
  1503. #endif
  1504. public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socket_flags,
  1505. AsyncCallback callback, object state)
  1506. {
  1507. if (disposed && closed)
  1508. throw new ObjectDisposedException (GetType ().ToString ());
  1509. if (buffer == null)
  1510. throw new ArgumentNullException ("buffer");
  1511. if (offset < 0)
  1512. throw new ArgumentOutOfRangeException ("offset", "offset must be >= 0");
  1513. if (size < 0)
  1514. throw new ArgumentOutOfRangeException ("size", "size must be >= 0");
  1515. if (offset + size > buffer.Length)
  1516. throw new ArgumentOutOfRangeException ("offset, size", "offset + size exceeds the buffer length");
  1517. #if NET_2_0
  1518. /* TODO: Check this exception in the 1.1 profile */
  1519. if (!connected)
  1520. throw new SocketException ((int)SocketError.NotConnected);
  1521. #endif
  1522. SocketAsyncResult req;
  1523. lock (writeQ) {
  1524. req = new SocketAsyncResult (this, state, callback, SocketOperation.Send);
  1525. req.Buffer = buffer;
  1526. req.Offset = offset;
  1527. req.Size = size;
  1528. req.SockFlags = socket_flags;
  1529. writeQ.Enqueue (req);
  1530. if (writeQ.Count == 1) {
  1531. Worker worker = new Worker (req);
  1532. SocketAsyncCall sac = new SocketAsyncCall (worker.Send);
  1533. sac.BeginInvoke (null, req);
  1534. }
  1535. }
  1536. return req;
  1537. }
  1538. #if NET_2_0
  1539. public IAsyncResult BeginSend (byte[] buffer, int offset,
  1540. int size,
  1541. SocketFlags socketFlags,
  1542. out SocketError errorCode,
  1543. AsyncCallback callback,
  1544. object state)
  1545. {
  1546. if (!connected) {
  1547. errorCode = SocketError.NotConnected;
  1548. throw new SocketException ((int)errorCode);
  1549. }
  1550. errorCode = SocketError.Success;
  1551. return (BeginSend (buffer, offset, size, socketFlags, callback,
  1552. state));
  1553. }
  1554. public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers,
  1555. SocketFlags socketFlags,
  1556. AsyncCallback callback,
  1557. object state)
  1558. {
  1559. if (disposed && closed)
  1560. throw new ObjectDisposedException (GetType ().ToString ());
  1561. if (buffers == null)
  1562. throw new ArgumentNullException ("buffers");
  1563. if (!connected)
  1564. throw new SocketException ((int)SocketError.NotConnected);
  1565. SocketAsyncResult req;
  1566. lock (writeQ) {
  1567. req = new SocketAsyncResult (this, state, callback, SocketOperation.Send);
  1568. req.Buffers = buffers;
  1569. req.SockFlags = socketFlags;
  1570. writeQ.Enqueue (req);
  1571. if (writeQ.Count == 1) {
  1572. Worker worker = new Worker (req);
  1573. SocketAsyncCall sac = new SocketAsyncCall (worker.Send);
  1574. sac.BeginInvoke (null, req);
  1575. }
  1576. }
  1577. return(req);
  1578. }
  1579. [CLSCompliant (false)]
  1580. public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers,
  1581. SocketFlags socketFlags,
  1582. out SocketError errorCode,
  1583. AsyncCallback callback,
  1584. object state)
  1585. {
  1586. if (!connected) {
  1587. errorCode = SocketError.NotConnected;
  1588. throw new SocketException ((int)errorCode);
  1589. }
  1590. errorCode = SocketError.Success;
  1591. return (BeginSend (buffers, socketFlags, callback, state));
  1592. }
  1593. [MonoTODO ("Not implemented")]
  1594. public IAsyncResult BeginSendFile (string fileName,
  1595. AsyncCallback callback,
  1596. object state)
  1597. {
  1598. if (disposed && closed)
  1599. throw new ObjectDisposedException (GetType ().ToString ());
  1600. if (!connected)
  1601. throw new NotSupportedException ();
  1602. if (!File.Exists (fileName))
  1603. throw new FileNotFoundException ();
  1604. throw new NotImplementedException ();
  1605. }
  1606. [MonoTODO ("Not implemented")]
  1607. public IAsyncResult BeginSendFile (string fileName,
  1608. byte[] preBuffer,
  1609. byte[] postBuffer,
  1610. TransmitFileOptions flags,
  1611. AsyncCallback callback,
  1612. object state)
  1613. {
  1614. if (disposed && closed)
  1615. throw new ObjectDisposedException (GetType ().ToString ());
  1616. if (!connected)
  1617. throw new NotSupportedException ();
  1618. if (!File.Exists (fileName))
  1619. throw new FileNotFoundException ();
  1620. throw new NotImplementedException ();
  1621. }
  1622. #endif
  1623. public IAsyncResult BeginSendTo(byte[] buffer, int offset,
  1624. int size,
  1625. SocketFlags socket_flags,
  1626. EndPoint remote_end,
  1627. AsyncCallback callback,
  1628. object state) {
  1629. if (disposed && closed)
  1630. throw new ObjectDisposedException (GetType ().ToString ());
  1631. if (buffer == null)
  1632. throw new ArgumentNullException ("buffer");
  1633. if (offset < 0)
  1634. throw new ArgumentOutOfRangeException ("offset", "offset must be >= 0");
  1635. if (size < 0)
  1636. throw new ArgumentOutOfRangeException ("size", "size must be >= 0");
  1637. if (offset + size > buffer.Length)
  1638. throw new ArgumentOutOfRangeException ("offset, size", "offset + size exceeds the buffer length");
  1639. SocketAsyncResult req;
  1640. lock (writeQ) {
  1641. req = new SocketAsyncResult (this, state, callback, SocketOperation.SendTo);
  1642. req.Buffer = buffer;
  1643. req.Offset = offset;
  1644. req.Size = size;
  1645. req.SockFlags = socket_flags;
  1646. req.EndPoint = remote_end;
  1647. writeQ.Enqueue (req);
  1648. if (writeQ.Count == 1) {
  1649. Worker worker = new Worker (req);
  1650. SocketAsyncCall sac = new SocketAsyncCall (worker.SendTo);
  1651. sac.BeginInvoke (null, req);
  1652. }
  1653. }
  1654. return req;
  1655. }
  1656. // Creates a new system socket, returning the handle
  1657. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1658. private extern static void Bind_internal(IntPtr sock,
  1659. SocketAddress sa,
  1660. out int error);
  1661. public void Bind(EndPoint local_end) {
  1662. if (disposed && closed)
  1663. throw new ObjectDisposedException (GetType ().ToString ());
  1664. if (local_end == null)
  1665. throw new ArgumentNullException("local_end");
  1666. int error;
  1667. Bind_internal(socket, local_end.Serialize(), out error);
  1668. if (error != 0)
  1669. throw new SocketException (error);
  1670. #if NET_2_0
  1671. if (error == 0)
  1672. isbound = true;
  1673. #endif
  1674. seed_endpoint = local_end;
  1675. }
  1676. // Closes the socket
  1677. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1678. private extern static void Close_internal(IntPtr socket, out int error);
  1679. public void Close()
  1680. {
  1681. ((IDisposable) this).Dispose ();
  1682. }
  1683. #if NET_2_0
  1684. public void Close (int timeout)
  1685. {
  1686. System.Timers.Timer close_timer = new System.Timers.Timer ();
  1687. close_timer.Elapsed += new ElapsedEventHandler (OnTimeoutClose);
  1688. close_timer.Interval = timeout * 1000;
  1689. close_timer.AutoReset = false;
  1690. close_timer.Enabled = true;
  1691. }
  1692. private void OnTimeoutClose (object source, ElapsedEventArgs e)
  1693. {
  1694. this.Close ();
  1695. }
  1696. public bool ConnectAsync (SocketAsyncEventArgs e)
  1697. {
  1698. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1699. if (disposed && closed)
  1700. throw new ObjectDisposedException (GetType ().ToString ());
  1701. if (islistening)
  1702. throw new InvalidOperationException ("You may not perform this operation after calling the Listen method.");
  1703. if (e.RemoteEndPoint == null)
  1704. throw new ArgumentNullException ("remoteEP", "Value cannot be null.");
  1705. if (e.BufferList != null)
  1706. throw new ArgumentException ("Multiple buffers cannot be used with this method.");
  1707. e.DoOperation (SocketAsyncOperation.Connect, this);
  1708. // We always return true for now
  1709. return true;
  1710. }
  1711. #endif
  1712. // Connects to the remote address
  1713. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1714. private extern static void Connect_internal(IntPtr sock,
  1715. SocketAddress sa,
  1716. out int error);
  1717. public void Connect(EndPoint remote_end) {
  1718. if (disposed && closed)
  1719. throw new ObjectDisposedException (GetType ().ToString ());
  1720. if (remote_end == null)
  1721. throw new ArgumentNullException("remote_end");
  1722. if (remote_end is IPEndPoint) {
  1723. IPEndPoint ep = (IPEndPoint) remote_end;
  1724. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
  1725. throw new SocketException ((int) SocketError.AddressNotAvailable);
  1726. }
  1727. #if NET_2_0
  1728. /* TODO: check this for the 1.1 profile too */
  1729. if (islistening)
  1730. throw new InvalidOperationException ();
  1731. #endif
  1732. SocketAddress serial = remote_end.Serialize ();
  1733. int error = 0;
  1734. blocking_thread = Thread.CurrentThread;
  1735. try {
  1736. Connect_internal (socket, serial, out error);
  1737. } catch (ThreadAbortException) {
  1738. if (disposed) {
  1739. Thread.ResetAbort ();
  1740. error = (int) SocketError.Interrupted;
  1741. }
  1742. } finally {
  1743. blocking_thread = null;
  1744. }
  1745. if (error != 0)
  1746. throw new SocketException (error);
  1747. connected=true;
  1748. #if NET_2_0
  1749. isbound = true;
  1750. #endif
  1751. seed_endpoint = remote_end;
  1752. }
  1753. #if NET_2_0
  1754. public void Connect (IPAddress address, int port)
  1755. {
  1756. Connect (new IPEndPoint (address, port));
  1757. }
  1758. public void Connect (IPAddress[] addresses, int port)
  1759. {
  1760. if (disposed && closed)
  1761. throw new ObjectDisposedException (GetType ().ToString ());
  1762. if (addresses == null)
  1763. throw new ArgumentNullException ("addresses");
  1764. if (this.AddressFamily != AddressFamily.InterNetwork &&
  1765. this.AddressFamily != AddressFamily.InterNetworkV6)
  1766. throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
  1767. if (islistening)
  1768. throw new InvalidOperationException ();
  1769. /* FIXME: do non-blocking sockets Poll here? */
  1770. foreach (IPAddress address in addresses) {
  1771. IPEndPoint iep = new IPEndPoint (address,
  1772. port);
  1773. SocketAddress serial = iep.Serialize ();
  1774. int error = 0;
  1775. Connect_internal (socket, serial, out error);
  1776. if (error == 0) {
  1777. connected = true;
  1778. seed_endpoint = iep;
  1779. return;
  1780. } else if (error != (int)SocketError.InProgress &&
  1781. error != (int)SocketError.WouldBlock) {
  1782. continue;
  1783. }
  1784. if (!blocking) {
  1785. Poll (-1, SelectMode.SelectWrite);
  1786. int success = (int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
  1787. if (success == 0) {
  1788. connected = true;
  1789. seed_endpoint = iep;
  1790. return;
  1791. }
  1792. }
  1793. }
  1794. }
  1795. public void Connect (string host, int port)
  1796. {
  1797. IPHostEntry hostent = Dns.GetHostEntry (host);
  1798. Connect (hostent.AddressList, port);
  1799. }
  1800. #if NET_2_0
  1801. public bool DisconnectAsync (SocketAsyncEventArgs e)
  1802. {
  1803. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1804. if (disposed && closed)
  1805. throw new ObjectDisposedException (GetType ().ToString ());
  1806. e.DoOperation (SocketAsyncOperation.Disconnect, this);
  1807. return true;
  1808. }
  1809. #endif
  1810. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1811. private extern static void Disconnect_internal(IntPtr sock,
  1812. bool reuse,
  1813. out int error);
  1814. /* According to the docs, the MS runtime will throw
  1815. * PlatformNotSupportedException if the platform is
  1816. * newer than w2k. We should be able to cope...
  1817. */
  1818. public void Disconnect (bool reuseSocket)
  1819. {
  1820. if (disposed && closed)
  1821. throw new ObjectDisposedException (GetType ().ToString ());
  1822. int error = 0;
  1823. Disconnect_internal (socket, reuseSocket, out error);
  1824. if (error != 0) {
  1825. if (error == 50) {
  1826. /* ERROR_NOT_SUPPORTED */
  1827. throw new PlatformNotSupportedException ();
  1828. } else {
  1829. throw new SocketException (error);
  1830. }
  1831. }
  1832. connected = false;
  1833. if (reuseSocket) {
  1834. /* Do managed housekeeping here... */
  1835. }
  1836. }
  1837. [MonoTODO ("Not implemented")]
  1838. public SocketInformation DuplicateAndClose (int targetProcessId)
  1839. {
  1840. /* Need to serialize this socket into a
  1841. * SocketInformation struct, but must study
  1842. * the MS implementation harder to figure out
  1843. * behaviour as documentation is lacking
  1844. */
  1845. throw new NotImplementedException ();
  1846. }
  1847. #endif
  1848. public Socket EndAccept (IAsyncResult result)
  1849. {
  1850. int bytes;
  1851. byte[] buffer;
  1852. return(EndAccept (out buffer, out bytes, result));
  1853. }
  1854. #if NET_2_0
  1855. public Socket EndAccept (out byte[] buffer,
  1856. IAsyncResult asyncResult)
  1857. {
  1858. int bytes;
  1859. return(EndAccept (out buffer, out bytes, asyncResult));
  1860. }
  1861. #endif
  1862. #if NET_2_0
  1863. public
  1864. #else
  1865. private
  1866. #endif
  1867. Socket EndAccept (out byte[] buffer, out int bytesTransferred,
  1868. IAsyncResult asyncResult)
  1869. {
  1870. if (disposed && closed)
  1871. throw new ObjectDisposedException (GetType ().ToString ());
  1872. if (asyncResult == null)
  1873. throw new ArgumentNullException ("asyncResult");
  1874. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  1875. if (req == null)
  1876. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  1877. if (!asyncResult.IsCompleted)
  1878. asyncResult.AsyncWaitHandle.WaitOne ();
  1879. req.CheckIfThrowDelayedException ();
  1880. buffer = req.Buffer;
  1881. bytesTransferred = req.Total;
  1882. return(req.Socket);
  1883. }
  1884. public void EndConnect (IAsyncResult result)
  1885. {
  1886. if (disposed && closed)
  1887. throw new ObjectDisposedException (GetType ().ToString ());
  1888. if (result == null)
  1889. throw new ArgumentNullException ("result");
  1890. SocketAsyncResult req = result as SocketAsyncResult;
  1891. if (req == null)
  1892. throw new ArgumentException ("Invalid IAsyncResult", "result");
  1893. if (!result.IsCompleted)
  1894. result.AsyncWaitHandle.WaitOne();
  1895. req.CheckIfThrowDelayedException();
  1896. }
  1897. #if NET_2_0
  1898. public void EndDisconnect (IAsyncResult asyncResult)
  1899. {
  1900. if (disposed && closed)
  1901. throw new ObjectDisposedException (GetType ().ToString ());
  1902. if (asyncResult == null)
  1903. throw new ArgumentNullException ("asyncResult");
  1904. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  1905. if (req == null)
  1906. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  1907. if (!asyncResult.IsCompleted)
  1908. asyncResult.AsyncWaitHandle.WaitOne ();
  1909. req.CheckIfThrowDelayedException ();
  1910. }
  1911. #endif
  1912. public int EndReceive (IAsyncResult result)
  1913. {
  1914. SocketError error;
  1915. return (EndReceive (result, out error));
  1916. }
  1917. #if NET_2_0
  1918. public
  1919. #else
  1920. private
  1921. #endif
  1922. int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
  1923. {
  1924. if (disposed && closed)
  1925. throw new ObjectDisposedException (GetType ().ToString ());
  1926. if (asyncResult == null)
  1927. throw new ArgumentNullException ("asyncResult");
  1928. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  1929. if (req == null)
  1930. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  1931. if (!asyncResult.IsCompleted)
  1932. asyncResult.AsyncWaitHandle.WaitOne ();
  1933. errorCode = req.ErrorCode;
  1934. req.CheckIfThrowDelayedException ();
  1935. return(req.Total);
  1936. }
  1937. public int EndReceiveFrom(IAsyncResult result, ref EndPoint end_point)
  1938. {
  1939. if (disposed && closed)
  1940. throw new ObjectDisposedException (GetType ().ToString ());
  1941. if (result == null)
  1942. throw new ArgumentNullException ("result");
  1943. SocketAsyncResult req = result as SocketAsyncResult;
  1944. if (req == null)
  1945. throw new ArgumentException ("Invalid IAsyncResult", "result");
  1946. if (!result.IsCompleted)
  1947. result.AsyncWaitHandle.WaitOne();
  1948. req.CheckIfThrowDelayedException();
  1949. end_point = req.EndPoint;
  1950. return req.Total;
  1951. }
  1952. #if NET_2_0
  1953. [MonoTODO]
  1954. public int EndReceiveMessageFrom (IAsyncResult asyncResult,
  1955. ref SocketFlags socketFlags,
  1956. ref EndPoint endPoint,
  1957. out IPPacketInformation ipPacketInformation)
  1958. {
  1959. if (disposed && closed)
  1960. throw new ObjectDisposedException (GetType ().ToString ());
  1961. if (asyncResult == null)
  1962. throw new ArgumentNullException ("asyncResult");
  1963. if (endPoint == null)
  1964. throw new ArgumentNullException ("endPoint");
  1965. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  1966. if (req == null)
  1967. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  1968. throw new NotImplementedException ();
  1969. }
  1970. #endif
  1971. public int EndSend (IAsyncResult result)
  1972. {
  1973. SocketError error;
  1974. return(EndSend (result, out error));
  1975. }
  1976. #if NET_2_0
  1977. public
  1978. #else
  1979. private
  1980. #endif
  1981. int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
  1982. {
  1983. if (disposed && closed)
  1984. throw new ObjectDisposedException (GetType ().ToString ());
  1985. if (asyncResult == null)
  1986. throw new ArgumentNullException ("asyncResult");
  1987. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  1988. if (req == null)
  1989. throw new ArgumentException ("Invalid IAsyncResult", "result");
  1990. if (!asyncResult.IsCompleted)
  1991. asyncResult.AsyncWaitHandle.WaitOne ();
  1992. errorCode = req.ErrorCode;
  1993. req.CheckIfThrowDelayedException ();
  1994. return(req.Total);
  1995. }
  1996. #if NET_2_0
  1997. [MonoTODO]
  1998. public void EndSendFile (IAsyncResult asyncResult)
  1999. {
  2000. if (disposed && closed)
  2001. throw new ObjectDisposedException (GetType ().ToString ());
  2002. if (asyncResult == null)
  2003. throw new ArgumentNullException ("asyncResult");
  2004. SocketAsyncResult req = asyncResult as SocketAsyncResult;
  2005. if (req == null)
  2006. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  2007. throw new NotImplementedException ();
  2008. }
  2009. #endif
  2010. public int EndSendTo (IAsyncResult result)
  2011. {
  2012. if (disposed && closed)
  2013. throw new ObjectDisposedException (GetType ().ToString ());
  2014. if (result == null)
  2015. throw new ArgumentNullException ("result");
  2016. SocketAsyncResult req = result as SocketAsyncResult;
  2017. if (req == null)
  2018. throw new ArgumentException ("Invalid IAsyncResult", "result");
  2019. if (!result.IsCompleted)
  2020. result.AsyncWaitHandle.WaitOne();
  2021. req.CheckIfThrowDelayedException();
  2022. return req.Total;
  2023. }
  2024. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2025. private extern static void GetSocketOption_obj_internal(IntPtr socket,
  2026. SocketOptionLevel level, SocketOptionName name, out object obj_val,
  2027. out int error);
  2028. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2029. private extern static void GetSocketOption_arr_internal(IntPtr socket,
  2030. SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val,
  2031. out int error);
  2032. public object GetSocketOption (SocketOptionLevel level, SocketOptionName name)
  2033. {
  2034. if (disposed && closed)
  2035. throw new ObjectDisposedException (GetType ().ToString ());
  2036. object obj_val;
  2037. int error;
  2038. GetSocketOption_obj_internal(socket, level, name, out obj_val,
  2039. out error);
  2040. if (error != 0)
  2041. throw new SocketException (error);
  2042. if (name == SocketOptionName.Linger) {
  2043. return((LingerOption)obj_val);
  2044. } else if (name==SocketOptionName.AddMembership ||
  2045. name==SocketOptionName.DropMembership) {
  2046. return((MulticastOption)obj_val);
  2047. } else if (obj_val is int) {
  2048. return((int)obj_val);
  2049. } else {
  2050. return(obj_val);
  2051. }
  2052. }
  2053. public void GetSocketOption (SocketOptionLevel level, SocketOptionName name, byte [] opt_value)
  2054. {
  2055. if (disposed && closed)
  2056. throw new ObjectDisposedException (GetType ().ToString ());
  2057. int error;
  2058. GetSocketOption_arr_internal(socket, level, name, ref opt_value,
  2059. out error);
  2060. if (error != 0)
  2061. throw new SocketException (error);
  2062. }
  2063. public byte [] GetSocketOption (SocketOptionLevel level, SocketOptionName name, int length)
  2064. {
  2065. if (disposed && closed)
  2066. throw new ObjectDisposedException (GetType ().ToString ());
  2067. byte[] byte_val=new byte[length];
  2068. int error;
  2069. GetSocketOption_arr_internal(socket, level, name, ref byte_val,
  2070. out error);
  2071. if (error != 0)
  2072. throw new SocketException (error);
  2073. return(byte_val);
  2074. }
  2075. // See Socket.IOControl, WSAIoctl documentation in MSDN. The
  2076. // common options between UNIX and Winsock are FIONREAD,
  2077. // FIONBIO and SIOCATMARK. Anything else will depend on the
  2078. // system.
  2079. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2080. extern static int WSAIoctl (IntPtr sock, int ioctl_code, byte [] input,
  2081. byte [] output, out int error);
  2082. public int IOControl (int ioctl_code, byte [] in_value, byte [] out_value)
  2083. {
  2084. if (disposed)
  2085. throw new ObjectDisposedException (GetType ().ToString ());
  2086. int error;
  2087. int result = WSAIoctl (socket, ioctl_code, in_value, out_value,
  2088. out error);
  2089. if (error != 0)
  2090. throw new SocketException (error);
  2091. if (result == -1)
  2092. throw new InvalidOperationException ("Must use Blocking property instead.");
  2093. return result;
  2094. }
  2095. #if NET_2_0
  2096. [MonoTODO]
  2097. public int IOControl (IOControlCode ioControlCode,
  2098. byte[] optionInValue,
  2099. byte[] optionOutValue)
  2100. {
  2101. /* Probably just needs to mirror the int
  2102. * overload, but more investigation needed.
  2103. */
  2104. throw new NotImplementedException ();
  2105. }
  2106. #endif
  2107. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2108. private extern static void Listen_internal(IntPtr sock, int backlog,
  2109. out int error);
  2110. public void Listen (int backlog)
  2111. {
  2112. if (disposed && closed)
  2113. throw new ObjectDisposedException (GetType ().ToString ());
  2114. #if NET_2_0
  2115. /* TODO: check if this should be thrown in the
  2116. * 1.1 profile too
  2117. */
  2118. if (!isbound)
  2119. throw new SocketException ((int)SocketError.InvalidArgument);
  2120. #endif
  2121. int error;
  2122. Listen_internal(socket, backlog, out error);
  2123. if (error != 0)
  2124. throw new SocketException (error);
  2125. #if NET_2_0
  2126. islistening = true;
  2127. #endif
  2128. }
  2129. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2130. extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
  2131. public bool Poll (int time_us, SelectMode mode)
  2132. {
  2133. if (disposed && closed)
  2134. throw new ObjectDisposedException (GetType ().ToString ());
  2135. if (mode != SelectMode.SelectRead &&
  2136. mode != SelectMode.SelectWrite &&
  2137. mode != SelectMode.SelectError)
  2138. throw new NotSupportedException ("'mode' parameter is not valid.");
  2139. int error;
  2140. bool result = Poll_internal (socket, mode, time_us, out error);
  2141. if (error != 0)
  2142. throw new SocketException (error);
  2143. if (mode == SelectMode.SelectWrite && result && !connected) {
  2144. /* Update the connected state; for
  2145. * non-blocking Connect()s this is
  2146. * when we can find out that the
  2147. * connect succeeded.
  2148. */
  2149. if ((int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error) == 0) {
  2150. connected = true;
  2151. }
  2152. }
  2153. return result;
  2154. }
  2155. /* This overload is needed as the async Connect method
  2156. * also needs to check the socket error status, but
  2157. * getsockopt(..., SO_ERROR) clears the error.
  2158. */
  2159. internal bool Poll (int time_us, SelectMode mode, out int socket_error)
  2160. {
  2161. if (disposed && closed)
  2162. throw new ObjectDisposedException (GetType ().ToString ());
  2163. if (mode != SelectMode.SelectRead &&
  2164. mode != SelectMode.SelectWrite &&
  2165. mode != SelectMode.SelectError)
  2166. throw new NotSupportedException ("'mode' parameter is not valid.");
  2167. int error;
  2168. bool result = Poll_internal (socket, mode, time_us, out error);
  2169. if (error != 0)
  2170. throw new SocketException (error);
  2171. socket_error = (int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
  2172. if (mode == SelectMode.SelectWrite && result) {
  2173. /* Update the connected state; for
  2174. * non-blocking Connect()s this is
  2175. * when we can find out that the
  2176. * connect succeeded.
  2177. */
  2178. if (socket_error == 0) {
  2179. connected = true;
  2180. }
  2181. }
  2182. return result;
  2183. }
  2184. #if NET_2_0
  2185. public bool ReceiveAsync (SocketAsyncEventArgs e)
  2186. {
  2187. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  2188. //
  2189. // LAME SPEC: the ArgumentException is never thrown, instead an NRE is
  2190. // thrown when e.Buffer and e.BufferList are null (works fine when one is
  2191. // set to a valid object)
  2192. if (disposed && closed)
  2193. throw new ObjectDisposedException (GetType ().ToString ());
  2194. // We do not support recv into multiple buffers yet
  2195. if (e.BufferList != null)
  2196. throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
  2197. e.DoOperation (SocketAsyncOperation.Receive, this);
  2198. // We always return true for now
  2199. return true;
  2200. }
  2201. #endif
  2202. public int Receive (byte [] buf)
  2203. {
  2204. if (disposed && closed)
  2205. throw new ObjectDisposedException (GetType ().ToString ());
  2206. if (buf == null)
  2207. throw new ArgumentNullException ("buf");
  2208. SocketError error;
  2209. int ret = Receive_nochecks (buf, 0, buf.Length, SocketFlags.None, out error);
  2210. if (error != SocketError.Success)
  2211. throw new SocketException ((int) error);
  2212. return ret;
  2213. }
  2214. public int Receive (byte [] buf, SocketFlags flags)
  2215. {
  2216. if (disposed && closed)
  2217. throw new ObjectDisposedException (GetType ().ToString ());
  2218. if (buf == null)
  2219. throw new ArgumentNullException ("buf");
  2220. SocketError error;
  2221. int ret = Receive_nochecks (buf, 0, buf.Length, flags, out error);
  2222. if (error != SocketError.Success) {
  2223. if (error == SocketError.WouldBlock && blocking) // This might happen when ReceiveTimeout is set
  2224. throw new SocketException ((int) error, "Operation timed out.");
  2225. throw new SocketException ((int) error);
  2226. }
  2227. return ret;
  2228. }
  2229. public int Receive (byte [] buf, int size, SocketFlags flags)
  2230. {
  2231. if (disposed && closed)
  2232. throw new ObjectDisposedException (GetType ().ToString ());
  2233. if (buf == null)
  2234. throw new ArgumentNullException ("buf");
  2235. if (size < 0 || size > buf.Length)
  2236. throw new ArgumentOutOfRangeException ("size");
  2237. SocketError error;
  2238. int ret = Receive_nochecks (buf, 0, size, flags, out error);
  2239. if (error != SocketError.Success) {
  2240. if (error == SocketError.WouldBlock && blocking) // This might happen when ReceiveTimeout is set
  2241. throw new SocketException ((int) error, "Operation timed out.");
  2242. throw new SocketException ((int) error);
  2243. }
  2244. return ret;
  2245. }
  2246. public int Receive (byte [] buf, int offset, int size, SocketFlags flags)
  2247. {
  2248. if (disposed && closed)
  2249. throw new ObjectDisposedException (GetType ().ToString ());
  2250. if (buf == null)
  2251. throw new ArgumentNullException ("buf");
  2252. if (offset < 0 || offset > buf.Length)
  2253. throw new ArgumentOutOfRangeException ("offset");
  2254. if (size < 0 || offset + size > buf.Length)
  2255. throw new ArgumentOutOfRangeException ("size");
  2256. SocketError error;
  2257. int ret = Receive_nochecks (buf, offset, size, flags, out error);
  2258. if (error != SocketError.Success) {
  2259. if (error == SocketError.WouldBlock && blocking) // This might happen when ReceiveTimeout is set
  2260. throw new SocketException ((int) error, "Operation timed out.");
  2261. throw new SocketException ((int) error);
  2262. }
  2263. return ret;
  2264. }
  2265. #if NET_2_0
  2266. public int Receive (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  2267. {
  2268. if (disposed && closed)
  2269. throw new ObjectDisposedException (GetType ().ToString ());
  2270. if (buf == null)
  2271. throw new ArgumentNullException ("buf");
  2272. if (offset < 0 || offset > buf.Length)
  2273. throw new ArgumentOutOfRangeException ("offset");
  2274. if (size < 0 || offset + size > buf.Length)
  2275. throw new ArgumentOutOfRangeException ("size");
  2276. return Receive_nochecks (buf, offset, size, flags, out error);
  2277. }
  2278. [MonoTODO]
  2279. public int Receive (IList<ArraySegment<byte>> buffers)
  2280. {
  2281. /* For these generic IList overloads I need to
  2282. * implement WSARecv in the runtime
  2283. */
  2284. throw new NotImplementedException ();
  2285. }
  2286. [CLSCompliant (false)]
  2287. [MonoTODO]
  2288. public int Receive (IList<ArraySegment<byte>> buffers,
  2289. SocketFlags socketFlags)
  2290. {
  2291. throw new NotImplementedException ();
  2292. }
  2293. [CLSCompliant (false)]
  2294. [MonoTODO]
  2295. public int Receive (IList<ArraySegment<byte>> buffers,
  2296. SocketFlags socketFlags,
  2297. out SocketError errorCode)
  2298. {
  2299. throw new NotImplementedException ();
  2300. }
  2301. #endif
  2302. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2303. private extern static int Receive_internal(IntPtr sock,
  2304. byte[] buffer,
  2305. int offset,
  2306. int count,
  2307. SocketFlags flags,
  2308. out int error);
  2309. internal int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  2310. {
  2311. int nativeError;
  2312. int ret = Receive_internal (socket, buf, offset, size, flags, out nativeError);
  2313. error = (SocketError) nativeError;
  2314. if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress)
  2315. connected = false;
  2316. else
  2317. connected = true;
  2318. return ret;
  2319. }
  2320. #if NET_2_0
  2321. public bool ReceiveFromAsync (SocketAsyncEventArgs e)
  2322. {
  2323. if (disposed && closed)
  2324. throw new ObjectDisposedException (GetType ().ToString ());
  2325. // We do not support recv into multiple buffers yet
  2326. if (e.BufferList != null)
  2327. throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
  2328. if (e.RemoteEndPoint == null)
  2329. throw new ArgumentNullException ("remoteEP", "Value cannot be null.");
  2330. e.DoOperation (SocketAsyncOperation.ReceiveFrom, this);
  2331. // We always return true for now
  2332. return true;
  2333. }
  2334. #endif
  2335. public int ReceiveFrom (byte [] buf, ref EndPoint remote_end)
  2336. {
  2337. if (disposed && closed)
  2338. throw new ObjectDisposedException (GetType ().ToString ());
  2339. if (buf == null)
  2340. throw new ArgumentNullException ("buf");
  2341. if (remote_end == null)
  2342. throw new ArgumentNullException ("remote_end");
  2343. return ReceiveFrom_nochecks (buf, 0, buf.Length, SocketFlags.None, ref remote_end);
  2344. }
  2345. public int ReceiveFrom (byte [] buf, SocketFlags flags, ref EndPoint remote_end)
  2346. {
  2347. if (disposed && closed)
  2348. throw new ObjectDisposedException (GetType ().ToString ());
  2349. if (buf == null)
  2350. throw new ArgumentNullException ("buf");
  2351. if (remote_end == null)
  2352. throw new ArgumentNullException ("remote_end");
  2353. return ReceiveFrom_nochecks (buf, 0, buf.Length, flags, ref remote_end);
  2354. }
  2355. public int ReceiveFrom (byte [] buf, int size, SocketFlags flags,
  2356. ref EndPoint remote_end)
  2357. {
  2358. if (disposed && closed)
  2359. throw new ObjectDisposedException (GetType ().ToString ());
  2360. if (buf == null)
  2361. throw new ArgumentNullException ("buf");
  2362. if (remote_end == null)
  2363. throw new ArgumentNullException ("remote_end");
  2364. if (size < 0 || size > buf.Length)
  2365. throw new ArgumentOutOfRangeException ("size");
  2366. return ReceiveFrom_nochecks (buf, 0, size, flags, ref remote_end);
  2367. }
  2368. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2369. private extern static int RecvFrom_internal(IntPtr sock,
  2370. byte[] buffer,
  2371. int offset,
  2372. int count,
  2373. SocketFlags flags,
  2374. ref SocketAddress sockaddr,
  2375. out int error);
  2376. public int ReceiveFrom (byte [] buf, int offset, int size, SocketFlags flags,
  2377. ref EndPoint remote_end)
  2378. {
  2379. if (disposed && closed)
  2380. throw new ObjectDisposedException (GetType ().ToString ());
  2381. if (buf == null)
  2382. throw new ArgumentNullException ("buf");
  2383. if (remote_end == null)
  2384. throw new ArgumentNullException ("remote_end");
  2385. if (offset < 0 || offset > buf.Length)
  2386. throw new ArgumentOutOfRangeException ("offset");
  2387. if (size < 0 || offset + size > buf.Length)
  2388. throw new ArgumentOutOfRangeException ("size");
  2389. return ReceiveFrom_nochecks (buf, offset, size, flags, ref remote_end);
  2390. }
  2391. internal int ReceiveFrom_nochecks (byte [] buf, int offset, int size, SocketFlags flags,
  2392. ref EndPoint remote_end)
  2393. {
  2394. SocketAddress sockaddr = remote_end.Serialize();
  2395. int cnt, error;
  2396. cnt = RecvFrom_internal (socket, buf, offset, size, flags, ref sockaddr, out error);
  2397. SocketError err = (SocketError) error;
  2398. if (err != 0) {
  2399. if (err != SocketError.WouldBlock && err != SocketError.InProgress)
  2400. connected = false;
  2401. else if (err == SocketError.WouldBlock && blocking) // This might happen when ReceiveTimeout is set
  2402. throw new SocketException (error, "Operation timed out.");
  2403. throw new SocketException (error);
  2404. }
  2405. connected = true;
  2406. #if NET_2_0
  2407. isbound = true;
  2408. #endif
  2409. // If sockaddr is null then we're a connection
  2410. // oriented protocol and should ignore the
  2411. // remote_end parameter (see MSDN
  2412. // documentation for Socket.ReceiveFrom(...) )
  2413. if ( sockaddr != null ) {
  2414. // Stupidly, EndPoint.Create() is an
  2415. // instance method
  2416. remote_end = remote_end.Create (sockaddr);
  2417. }
  2418. seed_endpoint = remote_end;
  2419. return cnt;
  2420. }
  2421. #if NET_2_0
  2422. [MonoTODO ("Not implemented")]
  2423. public bool ReceiveMessageFromAsync (SocketAsyncEventArgs e)
  2424. {
  2425. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  2426. if (disposed && closed)
  2427. throw new ObjectDisposedException (GetType ().ToString ());
  2428. throw new NotImplementedException ();
  2429. }
  2430. [MonoTODO ("Not implemented")]
  2431. public int ReceiveMessageFrom (byte[] buffer, int offset,
  2432. int size,
  2433. ref SocketFlags socketFlags,
  2434. ref EndPoint remoteEP,
  2435. out IPPacketInformation ipPacketInformation)
  2436. {
  2437. if (disposed && closed)
  2438. throw new ObjectDisposedException (GetType ().ToString ());
  2439. if (buffer == null)
  2440. throw new ArgumentNullException ("buffer");
  2441. if (remoteEP == null)
  2442. throw new ArgumentNullException ("remoteEP");
  2443. if (offset < 0 || offset > buffer.Length)
  2444. throw new ArgumentOutOfRangeException ("offset");
  2445. if (size < 0 || offset + size > buffer.Length)
  2446. throw new ArgumentOutOfRangeException ("size");
  2447. /* FIXME: figure out how we get hold of the
  2448. * IPPacketInformation
  2449. */
  2450. throw new NotImplementedException ();
  2451. }
  2452. [MonoTODO ("Not implemented")]
  2453. public bool SendPacketsAsync (SocketAsyncEventArgs e)
  2454. {
  2455. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  2456. if (disposed && closed)
  2457. throw new ObjectDisposedException (GetType ().ToString ());
  2458. throw new NotImplementedException ();
  2459. }
  2460. public bool SendAsync (SocketAsyncEventArgs e)
  2461. {
  2462. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  2463. if (disposed && closed)
  2464. throw new ObjectDisposedException (GetType ().ToString ());
  2465. if (e.Buffer == null && e.BufferList == null)
  2466. throw new ArgumentException ("Either e.Buffer or e.BufferList must be valid buffers.");
  2467. e.DoOperation (SocketAsyncOperation.Send, this);
  2468. // We always return true for now
  2469. return true;
  2470. }
  2471. #endif
  2472. public int Send (byte [] buf)
  2473. {
  2474. if (disposed && closed)
  2475. throw new ObjectDisposedException (GetType ().ToString ());
  2476. if (buf == null)
  2477. throw new ArgumentNullException ("buf");
  2478. SocketError error;
  2479. int ret = Send_nochecks (buf, 0, buf.Length, SocketFlags.None, out error);
  2480. if (error != SocketError.Success)
  2481. throw new SocketException ((int) error);
  2482. return ret;
  2483. }
  2484. public int Send (byte [] buf, SocketFlags flags)
  2485. {
  2486. if (disposed && closed)
  2487. throw new ObjectDisposedException (GetType ().ToString ());
  2488. if (buf == null)
  2489. throw new ArgumentNullException ("buf");
  2490. SocketError error;
  2491. int ret = Send_nochecks (buf, 0, buf.Length, flags, out error);
  2492. if (error != SocketError.Success)
  2493. throw new SocketException ((int) error);
  2494. return ret;
  2495. }
  2496. public int Send (byte [] buf, int size, SocketFlags flags)
  2497. {
  2498. if (disposed && closed)
  2499. throw new ObjectDisposedException (GetType ().ToString ());
  2500. if (buf == null)
  2501. throw new ArgumentNullException ("buf");
  2502. if (size < 0 || size > buf.Length)
  2503. throw new ArgumentOutOfRangeException ("size");
  2504. SocketError error;
  2505. int ret = Send_nochecks (buf, 0, size, flags, out error);
  2506. if (error != SocketError.Success)
  2507. throw new SocketException ((int) error);
  2508. return ret;
  2509. }
  2510. public int Send (byte [] buf, int offset, int size, SocketFlags flags)
  2511. {
  2512. if (disposed && closed)
  2513. throw new ObjectDisposedException (GetType ().ToString ());
  2514. if (buf == null)
  2515. throw new ArgumentNullException ("buffer");
  2516. if (offset < 0 || offset > buf.Length)
  2517. throw new ArgumentOutOfRangeException ("offset");
  2518. if (size < 0 || offset + size > buf.Length)
  2519. throw new ArgumentOutOfRangeException ("size");
  2520. SocketError error;
  2521. int ret = Send_nochecks (buf, offset, size, flags, out error);
  2522. if (error != SocketError.Success)
  2523. throw new SocketException ((int) error);
  2524. return ret;
  2525. }
  2526. #if NET_2_0
  2527. public int Send (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  2528. {
  2529. if (disposed && closed)
  2530. throw new ObjectDisposedException (GetType ().ToString ());
  2531. if (buf == null)
  2532. throw new ArgumentNullException ("buffer");
  2533. if (offset < 0 || offset > buf.Length)
  2534. throw new ArgumentOutOfRangeException ("offset");
  2535. if (size < 0 || offset + size > buf.Length)
  2536. throw new ArgumentOutOfRangeException ("size");
  2537. return Send_nochecks (buf, offset, size, flags, out error);
  2538. }
  2539. [MonoTODO]
  2540. public int Send (IList<ArraySegment<byte>> buffers)
  2541. {
  2542. /* For these generic IList overloads I need to
  2543. * implement WSASend in the runtime
  2544. */
  2545. throw new NotImplementedException ();
  2546. }
  2547. [MonoTODO]
  2548. public int Send (IList<ArraySegment<byte>> buffers,
  2549. SocketFlags socketFlags)
  2550. {
  2551. throw new NotImplementedException ();
  2552. }
  2553. [CLSCompliant (false)]
  2554. [MonoTODO]
  2555. public int Send (IList<ArraySegment<byte>> buffers,
  2556. SocketFlags socketFlags,
  2557. out SocketError errorCode)
  2558. {
  2559. throw new NotImplementedException ();
  2560. }
  2561. #endif
  2562. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2563. private extern static int Send_internal(IntPtr sock,
  2564. byte[] buf, int offset,
  2565. int count,
  2566. SocketFlags flags,
  2567. out int error);
  2568. internal int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  2569. {
  2570. if (size == 0) {
  2571. error = SocketError.Success;
  2572. return 0;
  2573. }
  2574. int nativeError;
  2575. int ret = Send_internal (socket, buf, offset, size, flags, out nativeError);
  2576. error = (SocketError)nativeError;
  2577. if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress)
  2578. connected = false;
  2579. else
  2580. connected = true;
  2581. return ret;
  2582. }
  2583. #if NET_2_0
  2584. [MonoTODO ("Not implemented")]
  2585. public void SendFile (string fileName)
  2586. {
  2587. if (disposed && closed)
  2588. throw new ObjectDisposedException (GetType ().ToString ());
  2589. if (!connected)
  2590. throw new NotSupportedException ();
  2591. if (!blocking)
  2592. throw new InvalidOperationException ();
  2593. if (!File.Exists (fileName))
  2594. throw new FileNotFoundException ();
  2595. /* FIXME: Implement TransmitFile */
  2596. throw new NotImplementedException ();
  2597. }
  2598. [MonoTODO ("Not implemented")]
  2599. public void SendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
  2600. {
  2601. if (disposed && closed)
  2602. throw new ObjectDisposedException (GetType ().ToString ());
  2603. if (!connected)
  2604. throw new NotSupportedException ();
  2605. if (!blocking)
  2606. throw new InvalidOperationException ();
  2607. if (!File.Exists (fileName))
  2608. throw new FileNotFoundException ();
  2609. /* FIXME: Implement TransmitFile */
  2610. throw new NotImplementedException ();
  2611. }
  2612. public bool SendToAsync (SocketAsyncEventArgs e)
  2613. {
  2614. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  2615. if (disposed && closed)
  2616. throw new ObjectDisposedException (GetType ().ToString ());
  2617. if (e.RemoteEndPoint == null)
  2618. throw new ArgumentNullException ("remoteEP", "Value cannot be null.");
  2619. e.DoOperation (SocketAsyncOperation.SendTo, this);
  2620. // We always return true for now
  2621. return true;
  2622. }
  2623. #endif
  2624. public int SendTo (byte [] buffer, EndPoint remote_end)
  2625. {
  2626. if (disposed && closed)
  2627. throw new ObjectDisposedException (GetType ().ToString ());
  2628. if (buffer == null)
  2629. throw new ArgumentNullException ("buffer");
  2630. if (remote_end == null)
  2631. throw new ArgumentNullException ("remote_end");
  2632. return SendTo_nochecks (buffer, 0, buffer.Length, SocketFlags.None, remote_end);
  2633. }
  2634. public int SendTo (byte [] buffer, SocketFlags flags, EndPoint remote_end)
  2635. {
  2636. if (disposed && closed)
  2637. throw new ObjectDisposedException (GetType ().ToString ());
  2638. if (buffer == null)
  2639. throw new ArgumentNullException ("buffer");
  2640. if (remote_end == null)
  2641. throw new ArgumentNullException ("remote_end");
  2642. return SendTo_nochecks (buffer, 0, buffer.Length, flags, remote_end);
  2643. }
  2644. public int SendTo (byte [] buffer, int size, SocketFlags flags, EndPoint remote_end)
  2645. {
  2646. if (disposed && closed)
  2647. throw new ObjectDisposedException (GetType ().ToString ());
  2648. if (buffer == null)
  2649. throw new ArgumentNullException ("buffer");
  2650. if (remote_end == null)
  2651. throw new ArgumentNullException ("remote_end");
  2652. if (size < 0 || size > buffer.Length)
  2653. throw new ArgumentOutOfRangeException ("size");
  2654. return SendTo_nochecks (buffer, 0, size, flags, remote_end);
  2655. }
  2656. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2657. private extern static int SendTo_internal(IntPtr sock,
  2658. byte[] buffer,
  2659. int offset,
  2660. int count,
  2661. SocketFlags flags,
  2662. SocketAddress sa,
  2663. out int error);
  2664. public int SendTo (byte [] buffer, int offset, int size, SocketFlags flags,
  2665. EndPoint remote_end)
  2666. {
  2667. if (disposed && closed)
  2668. throw new ObjectDisposedException (GetType ().ToString ());
  2669. if (buffer == null)
  2670. throw new ArgumentNullException ("buffer");
  2671. if (remote_end == null)
  2672. throw new ArgumentNullException("remote_end");
  2673. if (offset < 0 || offset > buffer.Length)
  2674. throw new ArgumentOutOfRangeException ("offset");
  2675. if (size < 0 || offset + size > buffer.Length)
  2676. throw new ArgumentOutOfRangeException ("size");
  2677. return SendTo_nochecks (buffer, offset, size, flags, remote_end);
  2678. }
  2679. internal int SendTo_nochecks (byte [] buffer, int offset, int size, SocketFlags flags,
  2680. EndPoint remote_end)
  2681. {
  2682. SocketAddress sockaddr = remote_end.Serialize ();
  2683. int ret, error;
  2684. ret = SendTo_internal (socket, buffer, offset, size, flags, sockaddr, out error);
  2685. SocketError err = (SocketError) error;
  2686. if (err != 0) {
  2687. if (err != SocketError.WouldBlock && err != SocketError.InProgress)
  2688. connected = false;
  2689. throw new SocketException (error);
  2690. }
  2691. connected = true;
  2692. #if NET_2_0
  2693. isbound = true;
  2694. #endif
  2695. seed_endpoint = remote_end;
  2696. return ret;
  2697. }
  2698. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2699. private extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level,
  2700. SocketOptionName name, object obj_val,
  2701. byte [] byte_val, int int_val,
  2702. out int error);
  2703. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, byte[] opt_value)
  2704. {
  2705. if (disposed && closed)
  2706. throw new ObjectDisposedException (GetType ().ToString ());
  2707. int error;
  2708. SetSocketOption_internal(socket, level, name, null,
  2709. opt_value, 0, out error);
  2710. if (error != 0)
  2711. throw new SocketException (error);
  2712. }
  2713. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, int opt_value)
  2714. {
  2715. if (disposed && closed)
  2716. throw new ObjectDisposedException (GetType ().ToString ());
  2717. int error;
  2718. SetSocketOption_internal(socket, level, name, null,
  2719. null, opt_value, out error);
  2720. if (error != 0)
  2721. throw new SocketException (error);
  2722. }
  2723. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, object opt_value)
  2724. {
  2725. if (disposed && closed)
  2726. throw new ObjectDisposedException (GetType ().ToString ());
  2727. if (opt_value == null)
  2728. throw new ArgumentNullException("opt_value");
  2729. int error;
  2730. /* From MS documentation on SetSocketOption: "For an
  2731. * option with a Boolean data type, specify a nonzero
  2732. * value to enable the option, and a zero value to
  2733. * disable the option."
  2734. * Booleans are only handled in 2.0
  2735. */
  2736. if (opt_value is System.Boolean) {
  2737. #if NET_2_0
  2738. bool bool_val = (bool) opt_value;
  2739. int int_val = (bool_val) ? 1 : 0;
  2740. SetSocketOption_internal (socket, level, name, null, null, int_val, out error);
  2741. #else
  2742. throw new ArgumentException ("Use an integer 1 (true) or 0 (false) instead of a boolean.", "opt_value");
  2743. #endif
  2744. } else {
  2745. SetSocketOption_internal (socket, level, name, opt_value, null, 0, out error);
  2746. }
  2747. if (error != 0)
  2748. throw new SocketException (error);
  2749. }
  2750. #if NET_2_0
  2751. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, bool optionValue)
  2752. {
  2753. if (disposed && closed)
  2754. throw new ObjectDisposedException (GetType ().ToString ());
  2755. int error;
  2756. int int_val = (optionValue) ? 1 : 0;
  2757. SetSocketOption_internal (socket, level, name, null, null, int_val, out error);
  2758. if (error != 0)
  2759. throw new SocketException (error);
  2760. }
  2761. #endif
  2762. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2763. private extern static void Shutdown_internal(IntPtr socket, SocketShutdown how, out int error);
  2764. public void Shutdown (SocketShutdown how)
  2765. {
  2766. if (disposed && closed)
  2767. throw new ObjectDisposedException (GetType ().ToString ());
  2768. int error;
  2769. Shutdown_internal (socket, how, out error);
  2770. if (error != 0)
  2771. throw new SocketException (error);
  2772. }
  2773. #if ONLY_1_1
  2774. public override int GetHashCode ()
  2775. {
  2776. // LAMESPEC:
  2777. // The socket is not suitable to serve as a hash code,
  2778. // because it will change during its lifetime, but
  2779. // this is how MS.NET 1.1 implemented this method.
  2780. return (int) socket;
  2781. }
  2782. #endif
  2783. protected virtual void Dispose (bool explicitDisposing)
  2784. {
  2785. if (disposed)
  2786. return;
  2787. disposed = true;
  2788. connected = false;
  2789. if ((int) socket != -1) {
  2790. int error;
  2791. closed = true;
  2792. IntPtr x = socket;
  2793. socket = (IntPtr) (-1);
  2794. Close_internal (x, out error);
  2795. if (blocking_thread != null) {
  2796. blocking_thread.Abort ();
  2797. blocking_thread = null;
  2798. }
  2799. if (error != 0)
  2800. throw new SocketException (error);
  2801. }
  2802. }
  2803. void IDisposable.Dispose ()
  2804. {
  2805. Dispose (true);
  2806. GC.SuppressFinalize (this);
  2807. }
  2808. ~Socket () {
  2809. Dispose (false);
  2810. }
  2811. }
  2812. }