Socket.cs 103 KB

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