Socket.cs 96 KB

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