Socket.cs 87 KB

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