Socket.cs 82 KB

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