Socket.cs 86 KB

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