Socket.cs 86 KB

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