2
0

Socket.cs 83 KB

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