Socket.cs 104 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482
  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. var ipEndPoint = local_end as IPEndPoint;
  938. if (ipEndPoint != null) {
  939. local_end = RemapIPEndPoint (ipEndPoint);
  940. }
  941. int error;
  942. Bind_internal (safe_handle, local_end.Serialize(), out error);
  943. if (error != 0)
  944. throw new SocketException (error);
  945. if (error == 0)
  946. is_bound = true;
  947. seed_endpoint = local_end;
  948. }
  949. private static void Bind_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
  950. {
  951. bool release = false;
  952. try {
  953. safeHandle.DangerousAddRef (ref release);
  954. Bind_internal (safeHandle.DangerousGetHandle (), sa, out error);
  955. } finally {
  956. if (release)
  957. safeHandle.DangerousRelease ();
  958. }
  959. }
  960. // Creates a new system socket, returning the handle
  961. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  962. private extern static void Bind_internal(IntPtr sock, SocketAddress sa, out int error);
  963. #endregion
  964. #region Listen
  965. public void Listen (int backlog)
  966. {
  967. ThrowIfDisposedAndClosed ();
  968. if (!is_bound)
  969. throw new SocketException ((int) SocketError.InvalidArgument);
  970. int error;
  971. Listen_internal(safe_handle, backlog, out error);
  972. if (error != 0)
  973. throw new SocketException (error);
  974. is_listening = true;
  975. }
  976. static void Listen_internal (SafeSocketHandle safeHandle, int backlog, out int error)
  977. {
  978. bool release = false;
  979. try {
  980. safeHandle.DangerousAddRef (ref release);
  981. Listen_internal (safeHandle.DangerousGetHandle (), backlog, out error);
  982. } finally {
  983. if (release)
  984. safeHandle.DangerousRelease ();
  985. }
  986. }
  987. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  988. extern static void Listen_internal (IntPtr sock, int backlog, out int error);
  989. #endregion
  990. #region Connect
  991. public void Connect (IPAddress address, int port)
  992. {
  993. Connect (new IPEndPoint (address, port));
  994. }
  995. public void Connect (string host, int port)
  996. {
  997. Connect (Dns.GetHostAddresses (host), port);
  998. }
  999. public void Connect (IPAddress[] addresses, int port)
  1000. {
  1001. ThrowIfDisposedAndClosed ();
  1002. if (addresses == null)
  1003. throw new ArgumentNullException ("addresses");
  1004. if (this.AddressFamily != AddressFamily.InterNetwork && this.AddressFamily != AddressFamily.InterNetworkV6)
  1005. throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
  1006. if (is_listening)
  1007. throw new InvalidOperationException ();
  1008. // FIXME: do non-blocking sockets Poll here?
  1009. int error = 0;
  1010. foreach (IPAddress address in addresses) {
  1011. IPEndPoint iep = new IPEndPoint (address, port);
  1012. iep = RemapIPEndPoint (iep);
  1013. Connect_internal (safe_handle, iep.Serialize (), out error);
  1014. if (error == 0) {
  1015. is_connected = true;
  1016. is_bound = true;
  1017. seed_endpoint = iep;
  1018. return;
  1019. }
  1020. if (error != (int)SocketError.InProgress && error != (int)SocketError.WouldBlock)
  1021. continue;
  1022. if (!is_blocking) {
  1023. Poll (-1, SelectMode.SelectWrite);
  1024. error = (int)GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
  1025. if (error == 0) {
  1026. is_connected = true;
  1027. is_bound = true;
  1028. seed_endpoint = iep;
  1029. return;
  1030. }
  1031. }
  1032. }
  1033. if (error != 0)
  1034. throw new SocketException (error);
  1035. }
  1036. public void Connect (EndPoint remoteEP)
  1037. {
  1038. ThrowIfDisposedAndClosed ();
  1039. if (remoteEP == null)
  1040. throw new ArgumentNullException ("remoteEP");
  1041. IPEndPoint ep = remoteEP as IPEndPoint;
  1042. /* Dgram uses Any to 'disconnect' */
  1043. if (ep != null && socket_type != SocketType.Dgram) {
  1044. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
  1045. throw new SocketException ((int) SocketError.AddressNotAvailable);
  1046. }
  1047. if (is_listening)
  1048. throw new InvalidOperationException ();
  1049. if (ep != null) {
  1050. remoteEP = RemapIPEndPoint (ep);
  1051. }
  1052. SocketAddress serial = remoteEP.Serialize ();
  1053. int error = 0;
  1054. Connect_internal (safe_handle, serial, out error);
  1055. if (error == 0 || error == 10035)
  1056. seed_endpoint = remoteEP; // Keep the ep around for non-blocking sockets
  1057. if (error != 0) {
  1058. if (is_closed)
  1059. error = SOCKET_CLOSED_CODE;
  1060. throw new SocketException (error);
  1061. }
  1062. is_connected = !(socket_type == SocketType.Dgram && ep != null && (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)));
  1063. is_bound = true;
  1064. }
  1065. public bool ConnectAsync (SocketAsyncEventArgs e)
  1066. {
  1067. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1068. ThrowIfDisposedAndClosed ();
  1069. if (is_listening)
  1070. throw new InvalidOperationException ("You may not perform this operation after calling the Listen method.");
  1071. if (e.RemoteEndPoint == null)
  1072. throw new ArgumentNullException ("remoteEP");
  1073. InitSocketAsyncEventArgs (e, ConnectAsyncCallback, e, SocketOperation.Connect);
  1074. try {
  1075. IPAddress [] addresses;
  1076. SocketAsyncResult ares;
  1077. if (!GetCheckedIPs (e, out addresses)) {
  1078. e.socket_async_result.EndPoint = e.RemoteEndPoint;
  1079. ares = (SocketAsyncResult) BeginConnect (e.RemoteEndPoint, ConnectAsyncCallback, e);
  1080. } else {
  1081. DnsEndPoint dep = (e.RemoteEndPoint as DnsEndPoint);
  1082. e.socket_async_result.Addresses = addresses;
  1083. e.socket_async_result.Port = dep.Port;
  1084. ares = (SocketAsyncResult) BeginConnect (addresses, dep.Port, ConnectAsyncCallback, e);
  1085. }
  1086. if (ares.IsCompleted && ares.CompletedSynchronously) {
  1087. ares.CheckIfThrowDelayedException ();
  1088. return false;
  1089. }
  1090. } catch (Exception exc) {
  1091. e.socket_async_result.Complete (exc, true);
  1092. return false;
  1093. }
  1094. return true;
  1095. }
  1096. static AsyncCallback ConnectAsyncCallback = new AsyncCallback (ares => {
  1097. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1098. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1099. throw new InvalidOperationException ("No operation in progress");
  1100. try {
  1101. e.current_socket.EndConnect (ares);
  1102. } catch (SocketException se) {
  1103. e.SocketError = se.SocketErrorCode;
  1104. } catch (ObjectDisposedException) {
  1105. e.SocketError = SocketError.OperationAborted;
  1106. } finally {
  1107. e.Complete ();
  1108. }
  1109. });
  1110. public IAsyncResult BeginConnect (IPAddress address, int port, AsyncCallback callback, object state)
  1111. {
  1112. ThrowIfDisposedAndClosed ();
  1113. if (address == null)
  1114. throw new ArgumentNullException ("address");
  1115. if (address.ToString ().Length == 0)
  1116. throw new ArgumentException ("The length of the IP address is zero");
  1117. if (port <= 0 || port > 65535)
  1118. throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
  1119. if (is_listening)
  1120. throw new InvalidOperationException ();
  1121. return BeginConnect (new IPEndPoint (address, port), callback, state);
  1122. }
  1123. public IAsyncResult BeginConnect (string host, int port, AsyncCallback callback, object state)
  1124. {
  1125. ThrowIfDisposedAndClosed ();
  1126. if (host == null)
  1127. throw new ArgumentNullException ("host");
  1128. if (address_family != AddressFamily.InterNetwork && address_family != AddressFamily.InterNetworkV6)
  1129. throw new NotSupportedException ("This method is valid only for sockets in the InterNetwork and InterNetworkV6 families");
  1130. if (port <= 0 || port > 65535)
  1131. throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
  1132. if (is_listening)
  1133. throw new InvalidOperationException ();
  1134. return BeginConnect (Dns.GetHostAddresses (host), port, callback, state);
  1135. }
  1136. public IAsyncResult BeginConnect (EndPoint end_point, AsyncCallback callback, object state)
  1137. {
  1138. ThrowIfDisposedAndClosed ();
  1139. if (end_point == null)
  1140. throw new ArgumentNullException ("end_point");
  1141. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
  1142. EndPoint = end_point,
  1143. };
  1144. // Bug #75154: Connect() should not succeed for .Any addresses.
  1145. if (end_point is IPEndPoint) {
  1146. IPEndPoint ep = (IPEndPoint) end_point;
  1147. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
  1148. sockares.Complete (new SocketException ((int) SocketError.AddressNotAvailable), true);
  1149. return sockares;
  1150. }
  1151. end_point = RemapIPEndPoint (ep);
  1152. }
  1153. int error = 0;
  1154. if (connect_in_progress) {
  1155. // This could happen when multiple IPs are used
  1156. // Calling connect() again will reset the connection attempt and cause
  1157. // an error. Better to just close the socket and move on.
  1158. connect_in_progress = false;
  1159. safe_handle.Dispose ();
  1160. safe_handle = new SafeSocketHandle (Socket_internal (address_family, socket_type, protocol_type, out error), true);
  1161. if (error != 0)
  1162. throw new SocketException (error);
  1163. }
  1164. bool blk = is_blocking;
  1165. if (blk)
  1166. Blocking = false;
  1167. Connect_internal (safe_handle, end_point.Serialize (), out error);
  1168. if (blk)
  1169. Blocking = true;
  1170. if (error == 0) {
  1171. // succeeded synch
  1172. is_connected = true;
  1173. is_bound = true;
  1174. sockares.Complete (true);
  1175. return sockares;
  1176. }
  1177. if (error != (int) SocketError.InProgress && error != (int) SocketError.WouldBlock) {
  1178. // error synch
  1179. is_connected = false;
  1180. is_bound = false;
  1181. sockares.Complete (new SocketException (error), true);
  1182. return sockares;
  1183. }
  1184. // continue asynch
  1185. is_connected = false;
  1186. is_bound = false;
  1187. connect_in_progress = true;
  1188. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginConnectCallback, sockares));
  1189. return sockares;
  1190. }
  1191. public IAsyncResult BeginConnect (IPAddress[] addresses, int port, AsyncCallback callback, object state)
  1192. {
  1193. ThrowIfDisposedAndClosed ();
  1194. if (addresses == null)
  1195. throw new ArgumentNullException ("addresses");
  1196. if (addresses.Length == 0)
  1197. throw new ArgumentException ("Empty addresses list");
  1198. if (this.AddressFamily != AddressFamily.InterNetwork && this.AddressFamily != AddressFamily.InterNetworkV6)
  1199. throw new NotSupportedException ("This method is only valid for addresses in the InterNetwork or InterNetworkV6 families");
  1200. if (port <= 0 || port > 65535)
  1201. throw new ArgumentOutOfRangeException ("port", "Must be > 0 and < 65536");
  1202. if (is_listening)
  1203. throw new InvalidOperationException ();
  1204. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Connect) {
  1205. Addresses = addresses,
  1206. Port = port,
  1207. };
  1208. is_connected = false;
  1209. return BeginMConnect (sockares);
  1210. }
  1211. internal IAsyncResult BeginMConnect (SocketAsyncResult sockares)
  1212. {
  1213. SocketAsyncResult ares = null;
  1214. Exception exc = null;
  1215. AsyncCallback callback;
  1216. for (int i = sockares.CurrentAddress; i < sockares.Addresses.Length; i++) {
  1217. try {
  1218. sockares.CurrentAddress++;
  1219. ares = (SocketAsyncResult) BeginConnect (new IPEndPoint (sockares.Addresses [i], sockares.Port), null, sockares);
  1220. if (ares.IsCompleted && ares.CompletedSynchronously) {
  1221. ares.CheckIfThrowDelayedException ();
  1222. callback = ares.AsyncCallback;
  1223. if (callback != null)
  1224. ThreadPool.UnsafeQueueUserWorkItem (_ => callback (ares), null);
  1225. }
  1226. break;
  1227. } catch (Exception e) {
  1228. exc = e;
  1229. ares = null;
  1230. }
  1231. }
  1232. if (ares == null)
  1233. throw exc;
  1234. return sockares;
  1235. }
  1236. static IOAsyncCallback BeginConnectCallback = new IOAsyncCallback (ares => {
  1237. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1238. if (sockares.EndPoint == null) {
  1239. sockares.Complete (new SocketException ((int)SocketError.AddressNotAvailable));
  1240. return;
  1241. }
  1242. SocketAsyncResult mconnect = sockares.AsyncState as SocketAsyncResult;
  1243. bool is_mconnect = mconnect != null && mconnect.Addresses != null;
  1244. try {
  1245. EndPoint ep = sockares.EndPoint;
  1246. int error_code = (int) sockares.socket.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
  1247. if (error_code == 0) {
  1248. if (is_mconnect)
  1249. sockares = mconnect;
  1250. sockares.socket.seed_endpoint = ep;
  1251. sockares.socket.is_connected = true;
  1252. sockares.socket.is_bound = true;
  1253. sockares.socket.connect_in_progress = false;
  1254. sockares.error = 0;
  1255. sockares.Complete ();
  1256. return;
  1257. }
  1258. if (!is_mconnect) {
  1259. sockares.socket.connect_in_progress = false;
  1260. sockares.Complete (new SocketException (error_code));
  1261. return;
  1262. }
  1263. if (mconnect.CurrentAddress >= mconnect.Addresses.Length) {
  1264. mconnect.Complete (new SocketException (error_code));
  1265. return;
  1266. }
  1267. mconnect.socket.BeginMConnect (mconnect);
  1268. } catch (Exception e) {
  1269. sockares.socket.connect_in_progress = false;
  1270. if (is_mconnect)
  1271. sockares = mconnect;
  1272. sockares.Complete (e);
  1273. return;
  1274. }
  1275. });
  1276. public void EndConnect (IAsyncResult result)
  1277. {
  1278. ThrowIfDisposedAndClosed ();
  1279. SocketAsyncResult sockares = ValidateEndIAsyncResult (result, "EndConnect", "result");
  1280. if (!sockares.IsCompleted)
  1281. sockares.AsyncWaitHandle.WaitOne();
  1282. sockares.CheckIfThrowDelayedException();
  1283. }
  1284. static void Connect_internal (SafeSocketHandle safeHandle, SocketAddress sa, out int error)
  1285. {
  1286. try {
  1287. safeHandle.RegisterForBlockingSyscall ();
  1288. Connect_internal (safeHandle.DangerousGetHandle (), sa, out error);
  1289. } finally {
  1290. safeHandle.UnRegisterForBlockingSyscall ();
  1291. }
  1292. }
  1293. /* Connects to the remote address */
  1294. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1295. extern static void Connect_internal(IntPtr sock, SocketAddress sa, out int error);
  1296. /* Returns :
  1297. * - false when it is ok to use RemoteEndPoint
  1298. * - true when addresses must be used (and addresses could be null/empty) */
  1299. bool GetCheckedIPs (SocketAsyncEventArgs e, out IPAddress [] addresses)
  1300. {
  1301. addresses = null;
  1302. // Connect to the first address that match the host name, like:
  1303. // http://blogs.msdn.com/ncl/archive/2009/07/20/new-ncl-features-in-net-4-0-beta-2.aspx
  1304. // while skipping entries that do not match the address family
  1305. DnsEndPoint dep = e.RemoteEndPoint as DnsEndPoint;
  1306. if (dep != null) {
  1307. addresses = Dns.GetHostAddresses (dep.Host);
  1308. return true;
  1309. } else {
  1310. e.ConnectByNameError = null;
  1311. return false;
  1312. }
  1313. }
  1314. #endregion
  1315. #region Disconnect
  1316. /* According to the docs, the MS runtime will throw PlatformNotSupportedException
  1317. * if the platform is newer than w2k. We should be able to cope... */
  1318. public void Disconnect (bool reuseSocket)
  1319. {
  1320. ThrowIfDisposedAndClosed ();
  1321. int error = 0;
  1322. Disconnect_internal (safe_handle, reuseSocket, out error);
  1323. if (error != 0) {
  1324. if (error == 50) {
  1325. /* ERROR_NOT_SUPPORTED */
  1326. throw new PlatformNotSupportedException ();
  1327. } else {
  1328. throw new SocketException (error);
  1329. }
  1330. }
  1331. is_connected = false;
  1332. if (reuseSocket) {
  1333. /* Do managed housekeeping here... */
  1334. }
  1335. }
  1336. public bool DisconnectAsync (SocketAsyncEventArgs e)
  1337. {
  1338. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1339. ThrowIfDisposedAndClosed ();
  1340. InitSocketAsyncEventArgs (e, DisconnectAsyncCallback, e, SocketOperation.Disconnect);
  1341. IOSelector.Add (e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginDisconnectCallback, e.socket_async_result));
  1342. return true;
  1343. }
  1344. static AsyncCallback DisconnectAsyncCallback = new AsyncCallback (ares => {
  1345. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1346. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1347. throw new InvalidOperationException ("No operation in progress");
  1348. try {
  1349. e.current_socket.EndDisconnect (ares);
  1350. } catch (SocketException ex) {
  1351. e.SocketError = ex.SocketErrorCode;
  1352. } catch (ObjectDisposedException) {
  1353. e.SocketError = SocketError.OperationAborted;
  1354. } finally {
  1355. e.Complete ();
  1356. }
  1357. });
  1358. public IAsyncResult BeginDisconnect (bool reuseSocket, AsyncCallback callback, object state)
  1359. {
  1360. ThrowIfDisposedAndClosed ();
  1361. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Disconnect) {
  1362. ReuseSocket = reuseSocket,
  1363. };
  1364. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginDisconnectCallback, sockares));
  1365. return sockares;
  1366. }
  1367. static IOAsyncCallback BeginDisconnectCallback = new IOAsyncCallback (ares => {
  1368. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1369. try {
  1370. sockares.socket.Disconnect (sockares.ReuseSocket);
  1371. } catch (Exception e) {
  1372. sockares.Complete (e);
  1373. return;
  1374. }
  1375. sockares.Complete ();
  1376. });
  1377. public void EndDisconnect (IAsyncResult asyncResult)
  1378. {
  1379. ThrowIfDisposedAndClosed ();
  1380. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndDisconnect", "asyncResult");
  1381. if (!sockares.IsCompleted)
  1382. sockares.AsyncWaitHandle.WaitOne ();
  1383. sockares.CheckIfThrowDelayedException ();
  1384. }
  1385. static void Disconnect_internal (SafeSocketHandle safeHandle, bool reuse, out int error)
  1386. {
  1387. bool release = false;
  1388. try {
  1389. safeHandle.DangerousAddRef (ref release);
  1390. Disconnect_internal (safeHandle.DangerousGetHandle (), reuse, out error);
  1391. } finally {
  1392. if (release)
  1393. safeHandle.DangerousRelease ();
  1394. }
  1395. }
  1396. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1397. extern static void Disconnect_internal (IntPtr sock, bool reuse, out int error);
  1398. #endregion
  1399. #region Receive
  1400. public int Receive (byte [] buffer)
  1401. {
  1402. return Receive (buffer, SocketFlags.None);
  1403. }
  1404. public int Receive (byte [] buffer, SocketFlags flags)
  1405. {
  1406. ThrowIfDisposedAndClosed ();
  1407. ThrowIfBufferNull (buffer);
  1408. ThrowIfBufferOutOfRange (buffer, 0, buffer.Length);
  1409. SocketError error;
  1410. int ret = Receive_nochecks (buffer, 0, buffer.Length, flags, out error);
  1411. if (error != SocketError.Success) {
  1412. if (error == SocketError.WouldBlock && is_blocking) // This might happen when ReceiveTimeout is set
  1413. throw new SocketException ((int) error, TIMEOUT_EXCEPTION_MSG);
  1414. throw new SocketException ((int) error);
  1415. }
  1416. return ret;
  1417. }
  1418. public int Receive (byte [] buffer, int size, SocketFlags flags)
  1419. {
  1420. ThrowIfDisposedAndClosed ();
  1421. ThrowIfBufferNull (buffer);
  1422. ThrowIfBufferOutOfRange (buffer, 0, size);
  1423. SocketError error;
  1424. int ret = Receive_nochecks (buffer, 0, size, flags, out error);
  1425. if (error != SocketError.Success) {
  1426. if (error == SocketError.WouldBlock && is_blocking) // This might happen when ReceiveTimeout is set
  1427. throw new SocketException ((int) error, TIMEOUT_EXCEPTION_MSG);
  1428. throw new SocketException ((int) error);
  1429. }
  1430. return ret;
  1431. }
  1432. public int Receive (byte [] buffer, int offset, int size, SocketFlags flags)
  1433. {
  1434. ThrowIfDisposedAndClosed ();
  1435. ThrowIfBufferNull (buffer);
  1436. ThrowIfBufferOutOfRange (buffer, offset, size);
  1437. SocketError error;
  1438. int ret = Receive_nochecks (buffer, offset, size, flags, out error);
  1439. if (error != SocketError.Success) {
  1440. if (error == SocketError.WouldBlock && is_blocking) // This might happen when ReceiveTimeout is set
  1441. throw new SocketException ((int) error, TIMEOUT_EXCEPTION_MSG);
  1442. throw new SocketException ((int) error);
  1443. }
  1444. return ret;
  1445. }
  1446. public int Receive (byte [] buffer, int offset, int size, SocketFlags flags, out SocketError error)
  1447. {
  1448. ThrowIfDisposedAndClosed ();
  1449. ThrowIfBufferNull (buffer);
  1450. ThrowIfBufferOutOfRange (buffer, offset, size);
  1451. return Receive_nochecks (buffer, offset, size, flags, out error);
  1452. }
  1453. public int Receive (IList<ArraySegment<byte>> buffers)
  1454. {
  1455. SocketError error;
  1456. int ret = Receive (buffers, SocketFlags.None, 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)
  1463. {
  1464. SocketError error;
  1465. int ret = Receive (buffers, socketFlags, out error);
  1466. if (error != SocketError.Success)
  1467. throw new SocketException ((int) error);
  1468. return(ret);
  1469. }
  1470. [CLSCompliant (false)]
  1471. public int Receive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
  1472. {
  1473. ThrowIfDisposedAndClosed ();
  1474. if (buffers == null || buffers.Count == 0)
  1475. throw new ArgumentNullException ("buffers");
  1476. int numsegments = buffers.Count;
  1477. int nativeError;
  1478. int ret;
  1479. /* Only example I can find of sending a byte array reference directly into an internal
  1480. * call is in System.Runtime.Remoting/System.Runtime.Remoting.Channels.Ipc.Win32/NamedPipeSocket.cs,
  1481. * so taking a lead from that... */
  1482. WSABUF[] bufarray = new WSABUF[numsegments];
  1483. GCHandle[] gch = new GCHandle[numsegments];
  1484. for (int i = 0; i < numsegments; i++) {
  1485. ArraySegment<byte> segment = buffers[i];
  1486. if (segment.Offset < 0 || segment.Count < 0 || segment.Count > segment.Array.Length - segment.Offset)
  1487. throw new ArgumentOutOfRangeException ("segment");
  1488. gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
  1489. bufarray[i].len = segment.Count;
  1490. bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
  1491. }
  1492. try {
  1493. ret = Receive_internal (safe_handle, bufarray, socketFlags, out nativeError);
  1494. } finally {
  1495. for (int i = 0; i < numsegments; i++) {
  1496. if (gch[i].IsAllocated)
  1497. gch[i].Free ();
  1498. }
  1499. }
  1500. errorCode = (SocketError) nativeError;
  1501. return ret;
  1502. }
  1503. public bool ReceiveAsync (SocketAsyncEventArgs e)
  1504. {
  1505. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1506. ThrowIfDisposedAndClosed ();
  1507. // LAME SPEC: the ArgumentException is never thrown, instead an NRE is
  1508. // thrown when e.Buffer and e.BufferList are null (works fine when one is
  1509. // set to a valid object)
  1510. if (e.Buffer == null && e.BufferList == null)
  1511. throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
  1512. if (e.Buffer == null) {
  1513. InitSocketAsyncEventArgs (e, ReceiveAsyncCallback, e, SocketOperation.ReceiveGeneric);
  1514. e.socket_async_result.Buffers = e.BufferList;
  1515. QueueIOSelectorJob (readQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, e.socket_async_result));
  1516. } else {
  1517. InitSocketAsyncEventArgs (e, ReceiveAsyncCallback, e, SocketOperation.Receive);
  1518. e.socket_async_result.Buffer = e.Buffer;
  1519. e.socket_async_result.Offset = e.Offset;
  1520. e.socket_async_result.Size = e.Count;
  1521. QueueIOSelectorJob (readQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, e.socket_async_result));
  1522. }
  1523. return true;
  1524. }
  1525. static AsyncCallback ReceiveAsyncCallback = new AsyncCallback (ares => {
  1526. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1527. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1528. throw new InvalidOperationException ("No operation in progress");
  1529. try {
  1530. e.BytesTransferred = e.current_socket.EndReceive (ares);
  1531. } catch (SocketException se){
  1532. e.SocketError = se.SocketErrorCode;
  1533. } catch (ObjectDisposedException) {
  1534. e.SocketError = SocketError.OperationAborted;
  1535. } finally {
  1536. e.Complete ();
  1537. }
  1538. });
  1539. public IAsyncResult BeginReceive (byte[] buffer, int offset, int size, SocketFlags socket_flags, AsyncCallback callback, object state)
  1540. {
  1541. ThrowIfDisposedAndClosed ();
  1542. ThrowIfBufferNull (buffer);
  1543. ThrowIfBufferOutOfRange (buffer, offset, size);
  1544. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Receive) {
  1545. Buffer = buffer,
  1546. Offset = offset,
  1547. Size = size,
  1548. SockFlags = socket_flags,
  1549. };
  1550. QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveCallback, sockares));
  1551. return sockares;
  1552. }
  1553. public IAsyncResult BeginReceive (byte[] buffer, int offset, int size, SocketFlags flags, out SocketError error, AsyncCallback callback, object state)
  1554. {
  1555. /* As far as I can tell from the docs and from experimentation, a pointer to the
  1556. * SocketError parameter is not supposed to be saved for the async parts. And as we don't
  1557. * set any socket errors in the setup code, we just have to set it to Success. */
  1558. error = SocketError.Success;
  1559. return BeginReceive (buffer, offset, size, flags, callback, state);
  1560. }
  1561. static IOAsyncCallback BeginReceiveCallback = new IOAsyncCallback (ares => {
  1562. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1563. int total = 0;
  1564. try {
  1565. total = Receive_internal (sockares.socket.safe_handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error);
  1566. } catch (Exception e) {
  1567. sockares.Complete (e);
  1568. return;
  1569. }
  1570. sockares.Complete (total);
  1571. });
  1572. [CLSCompliant (false)]
  1573. public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
  1574. {
  1575. ThrowIfDisposedAndClosed ();
  1576. if (buffers == null)
  1577. throw new ArgumentNullException ("buffers");
  1578. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.ReceiveGeneric) {
  1579. Buffers = buffers,
  1580. SockFlags = socketFlags,
  1581. };
  1582. QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveGenericCallback, sockares));
  1583. return sockares;
  1584. }
  1585. [CLSCompliant (false)]
  1586. public IAsyncResult BeginReceive (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
  1587. {
  1588. /* I assume the same SocketError semantics as above */
  1589. errorCode = SocketError.Success;
  1590. return BeginReceive (buffers, socketFlags, callback, state);
  1591. }
  1592. static IOAsyncCallback BeginReceiveGenericCallback = new IOAsyncCallback (ares => {
  1593. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1594. int total = 0;
  1595. try {
  1596. total = sockares.socket.Receive (sockares.Buffers, sockares.SockFlags);
  1597. } catch (Exception e) {
  1598. sockares.Complete (e);
  1599. return;
  1600. }
  1601. sockares.Complete (total);
  1602. });
  1603. public int EndReceive (IAsyncResult result)
  1604. {
  1605. SocketError error;
  1606. int bytesReceived = EndReceive (result, out error);
  1607. if (error != SocketError.Success) {
  1608. if (error != SocketError.WouldBlock && error != SocketError.InProgress)
  1609. is_connected = false;
  1610. throw new SocketException ((int)error);
  1611. }
  1612. return bytesReceived;
  1613. }
  1614. public int EndReceive (IAsyncResult asyncResult, out SocketError errorCode)
  1615. {
  1616. ThrowIfDisposedAndClosed ();
  1617. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndReceive", "asyncResult");
  1618. if (!sockares.IsCompleted)
  1619. sockares.AsyncWaitHandle.WaitOne ();
  1620. // If no socket error occurred, call CheckIfThrowDelayedException in case there are other
  1621. // kinds of exceptions that should be thrown.
  1622. if ((errorCode = sockares.ErrorCode) == SocketError.Success)
  1623. sockares.CheckIfThrowDelayedException();
  1624. return sockares.Total;
  1625. }
  1626. int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  1627. {
  1628. int nativeError;
  1629. int ret = Receive_internal (safe_handle, buf, offset, size, flags, out nativeError);
  1630. error = (SocketError) nativeError;
  1631. if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
  1632. is_connected = false;
  1633. is_bound = false;
  1634. } else {
  1635. is_connected = true;
  1636. }
  1637. return ret;
  1638. }
  1639. static int Receive_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error)
  1640. {
  1641. try {
  1642. safeHandle.RegisterForBlockingSyscall ();
  1643. return Receive_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error);
  1644. } finally {
  1645. safeHandle.UnRegisterForBlockingSyscall ();
  1646. }
  1647. }
  1648. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  1649. extern static int Receive_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
  1650. static int Receive_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, out int error)
  1651. {
  1652. try {
  1653. safeHandle.RegisterForBlockingSyscall ();
  1654. return Receive_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, out error);
  1655. } finally {
  1656. safeHandle.UnRegisterForBlockingSyscall ();
  1657. }
  1658. }
  1659. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1660. extern static int Receive_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, out int error);
  1661. #endregion
  1662. #region ReceiveFrom
  1663. public int ReceiveFrom (byte [] buffer, ref EndPoint remoteEP)
  1664. {
  1665. ThrowIfDisposedAndClosed ();
  1666. ThrowIfBufferNull (buffer);
  1667. return ReceiveFrom (buffer, 0, buffer.Length, SocketFlags.None, ref remoteEP);
  1668. }
  1669. public int ReceiveFrom (byte [] buffer, SocketFlags flags, ref EndPoint remoteEP)
  1670. {
  1671. ThrowIfDisposedAndClosed ();
  1672. ThrowIfBufferNull (buffer);
  1673. return ReceiveFrom (buffer, 0, buffer.Length, flags, ref remoteEP);
  1674. }
  1675. public int ReceiveFrom (byte [] buffer, int size, SocketFlags flags, ref EndPoint remoteEP)
  1676. {
  1677. ThrowIfDisposedAndClosed ();
  1678. ThrowIfBufferNull (buffer);
  1679. ThrowIfBufferOutOfRange (buffer, 0, size);
  1680. return ReceiveFrom (buffer, 0, size, flags, ref remoteEP);
  1681. }
  1682. public int ReceiveFrom (byte [] buffer, int offset, int size, SocketFlags flags, ref EndPoint remoteEP)
  1683. {
  1684. ThrowIfDisposedAndClosed ();
  1685. ThrowIfBufferNull (buffer);
  1686. ThrowIfBufferOutOfRange (buffer, offset, size);
  1687. if (remoteEP == null)
  1688. throw new ArgumentNullException ("remoteEP");
  1689. int error;
  1690. return ReceiveFrom_nochecks_exc (buffer, offset, size, flags, ref remoteEP, true, out error);
  1691. }
  1692. public bool ReceiveFromAsync (SocketAsyncEventArgs e)
  1693. {
  1694. ThrowIfDisposedAndClosed ();
  1695. // We do not support recv into multiple buffers yet
  1696. if (e.BufferList != null)
  1697. throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
  1698. if (e.RemoteEndPoint == null)
  1699. throw new ArgumentNullException ("remoteEP", "Value cannot be null.");
  1700. InitSocketAsyncEventArgs (e, ReceiveFromAsyncCallback, e, SocketOperation.ReceiveFrom);
  1701. e.socket_async_result.Buffer = e.Buffer;
  1702. e.socket_async_result.Offset = e.Offset;
  1703. e.socket_async_result.Size = e.Count;
  1704. e.socket_async_result.EndPoint = e.RemoteEndPoint;
  1705. e.socket_async_result.SockFlags = e.SocketFlags;
  1706. QueueIOSelectorJob (readQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, e.socket_async_result));
  1707. return true;
  1708. }
  1709. static AsyncCallback ReceiveFromAsyncCallback = new AsyncCallback (ares => {
  1710. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1711. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1712. throw new InvalidOperationException ("No operation in progress");
  1713. try {
  1714. e.BytesTransferred = e.current_socket.EndReceiveFrom (ares, ref e.remote_ep);
  1715. } catch (SocketException ex) {
  1716. e.SocketError = ex.SocketErrorCode;
  1717. } catch (ObjectDisposedException) {
  1718. e.SocketError = SocketError.OperationAborted;
  1719. } finally {
  1720. e.Complete ();
  1721. }
  1722. });
  1723. public IAsyncResult BeginReceiveFrom (byte[] buffer, int offset, int size, SocketFlags socket_flags, ref EndPoint remote_end, AsyncCallback callback, object state)
  1724. {
  1725. ThrowIfDisposedAndClosed ();
  1726. ThrowIfBufferNull (buffer);
  1727. ThrowIfBufferOutOfRange (buffer, offset, size);
  1728. if (remote_end == null)
  1729. throw new ArgumentNullException ("remote_end");
  1730. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.ReceiveFrom) {
  1731. Buffer = buffer,
  1732. Offset = offset,
  1733. Size = size,
  1734. SockFlags = socket_flags,
  1735. EndPoint = remote_end,
  1736. };
  1737. QueueIOSelectorJob (readQ, sockares.Handle, new IOSelectorJob (IOOperation.Read, BeginReceiveFromCallback, sockares));
  1738. return sockares;
  1739. }
  1740. static IOAsyncCallback BeginReceiveFromCallback = new IOAsyncCallback (ares => {
  1741. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  1742. int total = 0;
  1743. try {
  1744. int error;
  1745. total = sockares.socket.ReceiveFrom_nochecks_exc (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, ref sockares.EndPoint, true, out error);
  1746. } catch (Exception e) {
  1747. sockares.Complete (e);
  1748. return;
  1749. }
  1750. sockares.Complete (total);
  1751. });
  1752. public int EndReceiveFrom(IAsyncResult result, ref EndPoint end_point)
  1753. {
  1754. ThrowIfDisposedAndClosed ();
  1755. if (end_point == null)
  1756. throw new ArgumentNullException ("remote_end");
  1757. SocketAsyncResult sockares = ValidateEndIAsyncResult (result, "EndReceiveFrom", "result");
  1758. if (!sockares.IsCompleted)
  1759. sockares.AsyncWaitHandle.WaitOne();
  1760. sockares.CheckIfThrowDelayedException();
  1761. end_point = sockares.EndPoint;
  1762. return sockares.Total;
  1763. }
  1764. internal int ReceiveFrom_nochecks_exc (byte [] buf, int offset, int size, SocketFlags flags, ref EndPoint remote_end, bool throwOnError, out int error)
  1765. {
  1766. SocketAddress sockaddr = remote_end.Serialize();
  1767. int cnt = ReceiveFrom_internal (safe_handle, buf, offset, size, flags, ref sockaddr, out error);
  1768. SocketError err = (SocketError) error;
  1769. if (err != 0) {
  1770. if (err != SocketError.WouldBlock && err != SocketError.InProgress) {
  1771. is_connected = false;
  1772. } else if (err == SocketError.WouldBlock && is_blocking) { // This might happen when ReceiveTimeout is set
  1773. if (throwOnError)
  1774. throw new SocketException ((int) SocketError.TimedOut, TIMEOUT_EXCEPTION_MSG);
  1775. error = (int) SocketError.TimedOut;
  1776. return 0;
  1777. }
  1778. if (throwOnError)
  1779. throw new SocketException (error);
  1780. return 0;
  1781. }
  1782. is_connected = true;
  1783. is_bound = true;
  1784. /* If sockaddr is null then we're a connection oriented protocol and should ignore the
  1785. * remote_end parameter (see MSDN documentation for Socket.ReceiveFrom(...) ) */
  1786. if (sockaddr != null) {
  1787. /* Stupidly, EndPoint.Create() is an instance method */
  1788. remote_end = remote_end.Create (sockaddr);
  1789. }
  1790. seed_endpoint = remote_end;
  1791. return cnt;
  1792. }
  1793. static int ReceiveFrom_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error)
  1794. {
  1795. try {
  1796. safeHandle.RegisterForBlockingSyscall ();
  1797. return ReceiveFrom_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, ref sockaddr, out error);
  1798. } finally {
  1799. safeHandle.UnRegisterForBlockingSyscall ();
  1800. }
  1801. }
  1802. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1803. extern static int ReceiveFrom_internal(IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, ref SocketAddress sockaddr, out int error);
  1804. #endregion
  1805. #region ReceiveMessageFrom
  1806. [MonoTODO ("Not implemented")]
  1807. public int ReceiveMessageFrom (byte[] buffer, int offset, int size, ref SocketFlags socketFlags, ref EndPoint remoteEP, out IPPacketInformation ipPacketInformation)
  1808. {
  1809. ThrowIfDisposedAndClosed ();
  1810. ThrowIfBufferNull (buffer);
  1811. ThrowIfBufferOutOfRange (buffer, offset, size);
  1812. if (remoteEP == null)
  1813. throw new ArgumentNullException ("remoteEP");
  1814. // FIXME: figure out how we get hold of the IPPacketInformation
  1815. throw new NotImplementedException ();
  1816. }
  1817. [MonoTODO ("Not implemented")]
  1818. public bool ReceiveMessageFromAsync (SocketAsyncEventArgs e)
  1819. {
  1820. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1821. ThrowIfDisposedAndClosed ();
  1822. throw new NotImplementedException ();
  1823. }
  1824. [MonoTODO]
  1825. public IAsyncResult BeginReceiveMessageFrom (byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
  1826. {
  1827. ThrowIfDisposedAndClosed ();
  1828. ThrowIfBufferNull (buffer);
  1829. ThrowIfBufferOutOfRange (buffer, offset, size);
  1830. if (remoteEP == null)
  1831. throw new ArgumentNullException ("remoteEP");
  1832. throw new NotImplementedException ();
  1833. }
  1834. [MonoTODO]
  1835. public int EndReceiveMessageFrom (IAsyncResult asyncResult, ref SocketFlags socketFlags, ref EndPoint endPoint, out IPPacketInformation ipPacketInformation)
  1836. {
  1837. ThrowIfDisposedAndClosed ();
  1838. if (endPoint == null)
  1839. throw new ArgumentNullException ("endPoint");
  1840. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndReceiveMessageFrom", "asyncResult");
  1841. throw new NotImplementedException ();
  1842. }
  1843. #endregion
  1844. #region Send
  1845. public int Send (byte [] buffer)
  1846. {
  1847. ThrowIfDisposedAndClosed ();
  1848. ThrowIfBufferNull (buffer);
  1849. ThrowIfBufferOutOfRange (buffer, 0, buffer.Length);
  1850. SocketError error;
  1851. int ret = Send_nochecks (buffer, 0, buffer.Length, SocketFlags.None, out error);
  1852. if (error != SocketError.Success)
  1853. throw new SocketException ((int) error);
  1854. return ret;
  1855. }
  1856. public int Send (byte [] buffer, SocketFlags flags)
  1857. {
  1858. ThrowIfDisposedAndClosed ();
  1859. ThrowIfBufferNull (buffer);
  1860. ThrowIfBufferOutOfRange (buffer, 0, buffer.Length);
  1861. SocketError error;
  1862. int ret = Send_nochecks (buffer, 0, buffer.Length, flags, out error);
  1863. if (error != SocketError.Success)
  1864. throw new SocketException ((int) error);
  1865. return ret;
  1866. }
  1867. public int Send (byte [] buffer, int size, SocketFlags flags)
  1868. {
  1869. ThrowIfDisposedAndClosed ();
  1870. ThrowIfBufferNull (buffer);
  1871. ThrowIfBufferOutOfRange (buffer, 0, size);
  1872. SocketError error;
  1873. int ret = Send_nochecks (buffer, 0, size, flags, out error);
  1874. if (error != SocketError.Success)
  1875. throw new SocketException ((int) error);
  1876. return ret;
  1877. }
  1878. public int Send (byte [] buffer, int offset, int size, SocketFlags flags)
  1879. {
  1880. ThrowIfDisposedAndClosed ();
  1881. ThrowIfBufferNull (buffer);
  1882. ThrowIfBufferOutOfRange (buffer, offset, size);
  1883. SocketError error;
  1884. int ret = Send_nochecks (buffer, offset, size, flags, out error);
  1885. if (error != SocketError.Success)
  1886. throw new SocketException ((int) error);
  1887. return ret;
  1888. }
  1889. public int Send (byte [] buffer, int offset, int size, SocketFlags flags, out SocketError error)
  1890. {
  1891. ThrowIfDisposedAndClosed ();
  1892. ThrowIfBufferNull (buffer);
  1893. ThrowIfBufferOutOfRange (buffer, offset, size);
  1894. return Send_nochecks (buffer, offset, size, flags, out error);
  1895. }
  1896. public
  1897. int Send (IList<ArraySegment<byte>> buffers)
  1898. {
  1899. SocketError error;
  1900. int ret = Send (buffers, SocketFlags.None, out error);
  1901. if (error != SocketError.Success)
  1902. throw new SocketException ((int) error);
  1903. return ret;
  1904. }
  1905. public
  1906. int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags)
  1907. {
  1908. SocketError error;
  1909. int ret = Send (buffers, socketFlags, out error);
  1910. if (error != SocketError.Success)
  1911. throw new SocketException ((int) error);
  1912. return ret;
  1913. }
  1914. [CLSCompliant (false)]
  1915. public int Send (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode)
  1916. {
  1917. ThrowIfDisposedAndClosed ();
  1918. if (buffers == null)
  1919. throw new ArgumentNullException ("buffers");
  1920. if (buffers.Count == 0)
  1921. throw new ArgumentException ("Buffer is empty", "buffers");
  1922. int numsegments = buffers.Count;
  1923. int nativeError;
  1924. int ret;
  1925. WSABUF[] bufarray = new WSABUF[numsegments];
  1926. GCHandle[] gch = new GCHandle[numsegments];
  1927. for(int i = 0; i < numsegments; i++) {
  1928. ArraySegment<byte> segment = buffers[i];
  1929. if (segment.Offset < 0 || segment.Count < 0 || segment.Count > segment.Array.Length - segment.Offset)
  1930. throw new ArgumentOutOfRangeException ("segment");
  1931. gch[i] = GCHandle.Alloc (segment.Array, GCHandleType.Pinned);
  1932. bufarray[i].len = segment.Count;
  1933. bufarray[i].buf = Marshal.UnsafeAddrOfPinnedArrayElement (segment.Array, segment.Offset);
  1934. }
  1935. try {
  1936. ret = Send_internal (safe_handle, bufarray, socketFlags, out nativeError);
  1937. } finally {
  1938. for(int i = 0; i < numsegments; i++) {
  1939. if (gch[i].IsAllocated) {
  1940. gch[i].Free ();
  1941. }
  1942. }
  1943. }
  1944. errorCode = (SocketError)nativeError;
  1945. return ret;
  1946. }
  1947. int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  1948. {
  1949. if (size == 0) {
  1950. error = SocketError.Success;
  1951. return 0;
  1952. }
  1953. int nativeError;
  1954. int ret = Send_internal (safe_handle, buf, offset, size, flags, out nativeError);
  1955. error = (SocketError)nativeError;
  1956. if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress) {
  1957. is_connected = false;
  1958. is_bound = false;
  1959. } else {
  1960. is_connected = true;
  1961. }
  1962. return ret;
  1963. }
  1964. public bool SendAsync (SocketAsyncEventArgs e)
  1965. {
  1966. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  1967. ThrowIfDisposedAndClosed ();
  1968. if (e.Buffer == null && e.BufferList == null)
  1969. throw new NullReferenceException ("Either e.Buffer or e.BufferList must be valid buffers.");
  1970. if (e.Buffer == null) {
  1971. InitSocketAsyncEventArgs (e, SendAsyncCallback, e, SocketOperation.SendGeneric);
  1972. e.socket_async_result.Buffers = e.BufferList;
  1973. QueueIOSelectorJob (writeQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, e.socket_async_result));
  1974. } else {
  1975. InitSocketAsyncEventArgs (e, SendAsyncCallback, e, SocketOperation.Send);
  1976. e.socket_async_result.Buffer = e.Buffer;
  1977. e.socket_async_result.Offset = e.Offset;
  1978. e.socket_async_result.Size = e.Count;
  1979. QueueIOSelectorJob (writeQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
  1980. }
  1981. return true;
  1982. }
  1983. static AsyncCallback SendAsyncCallback = new AsyncCallback (ares => {
  1984. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  1985. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  1986. throw new InvalidOperationException ("No operation in progress");
  1987. try {
  1988. e.BytesTransferred = e.current_socket.EndSend (ares);
  1989. } catch (SocketException se){
  1990. e.SocketError = se.SocketErrorCode;
  1991. } catch (ObjectDisposedException) {
  1992. e.SocketError = SocketError.OperationAborted;
  1993. } finally {
  1994. e.Complete ();
  1995. }
  1996. });
  1997. public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
  1998. {
  1999. if (!is_connected) {
  2000. errorCode = SocketError.NotConnected;
  2001. throw new SocketException ((int) errorCode);
  2002. }
  2003. errorCode = SocketError.Success;
  2004. return BeginSend (buffer, offset, size, socketFlags, callback, state);
  2005. }
  2006. public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socket_flags, AsyncCallback callback, object state)
  2007. {
  2008. ThrowIfDisposedAndClosed ();
  2009. ThrowIfBufferNull (buffer);
  2010. ThrowIfBufferOutOfRange (buffer, offset, size);
  2011. if (!is_connected)
  2012. throw new SocketException ((int)SocketError.NotConnected);
  2013. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.Send) {
  2014. Buffer = buffer,
  2015. Offset = offset,
  2016. Size = size,
  2017. SockFlags = socket_flags,
  2018. };
  2019. QueueIOSelectorJob (writeQ, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, 0), sockares));
  2020. return sockares;
  2021. }
  2022. static void BeginSendCallback (SocketAsyncResult sockares, int sent_so_far)
  2023. {
  2024. int total = 0;
  2025. try {
  2026. total = Socket.Send_internal (sockares.socket.safe_handle, sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, out sockares.error);
  2027. } catch (Exception e) {
  2028. sockares.Complete (e);
  2029. return;
  2030. }
  2031. if (sockares.error == 0) {
  2032. sent_so_far += total;
  2033. sockares.Offset += total;
  2034. sockares.Size -= total;
  2035. if (sockares.socket.is_disposed) {
  2036. sockares.Complete (total);
  2037. return;
  2038. }
  2039. if (sockares.Size > 0) {
  2040. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendCallback ((SocketAsyncResult) s, sent_so_far), sockares));
  2041. return; // Have to finish writing everything. See bug #74475.
  2042. }
  2043. sockares.Total = sent_so_far;
  2044. }
  2045. sockares.Complete (total);
  2046. }
  2047. public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, AsyncCallback callback, object state)
  2048. {
  2049. ThrowIfDisposedAndClosed ();
  2050. if (buffers == null)
  2051. throw new ArgumentNullException ("buffers");
  2052. if (!is_connected)
  2053. throw new SocketException ((int)SocketError.NotConnected);
  2054. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.SendGeneric) {
  2055. Buffers = buffers,
  2056. SockFlags = socketFlags,
  2057. };
  2058. QueueIOSelectorJob (writeQ, sockares.Handle, new IOSelectorJob (IOOperation.Write, BeginSendGenericCallback, sockares));
  2059. return sockares;
  2060. }
  2061. [CLSCompliant (false)]
  2062. public IAsyncResult BeginSend (IList<ArraySegment<byte>> buffers, SocketFlags socketFlags, out SocketError errorCode, AsyncCallback callback, object state)
  2063. {
  2064. if (!is_connected) {
  2065. errorCode = SocketError.NotConnected;
  2066. throw new SocketException ((int)errorCode);
  2067. }
  2068. errorCode = SocketError.Success;
  2069. return BeginSend (buffers, socketFlags, callback, state);
  2070. }
  2071. static IOAsyncCallback BeginSendGenericCallback = new IOAsyncCallback (ares => {
  2072. SocketAsyncResult sockares = (SocketAsyncResult) ares;
  2073. int total = 0;
  2074. try {
  2075. total = sockares.socket.Send (sockares.Buffers, sockares.SockFlags);
  2076. } catch (Exception e) {
  2077. sockares.Complete (e);
  2078. return;
  2079. }
  2080. sockares.Complete (total);
  2081. });
  2082. public int EndSend (IAsyncResult result)
  2083. {
  2084. SocketError error;
  2085. int bytesSent = EndSend (result, out error);
  2086. if (error != SocketError.Success) {
  2087. if (error != SocketError.WouldBlock && error != SocketError.InProgress)
  2088. is_connected = false;
  2089. throw new SocketException ((int)error);
  2090. }
  2091. return bytesSent;
  2092. }
  2093. public int EndSend (IAsyncResult asyncResult, out SocketError errorCode)
  2094. {
  2095. ThrowIfDisposedAndClosed ();
  2096. SocketAsyncResult sockares = ValidateEndIAsyncResult (asyncResult, "EndSend", "asyncResult");
  2097. if (!sockares.IsCompleted)
  2098. sockares.AsyncWaitHandle.WaitOne ();
  2099. /* If no socket error occurred, call CheckIfThrowDelayedException in
  2100. * case there are other kinds of exceptions that should be thrown.*/
  2101. if ((errorCode = sockares.ErrorCode) == SocketError.Success)
  2102. sockares.CheckIfThrowDelayedException ();
  2103. return sockares.Total;
  2104. }
  2105. static int Send_internal (SafeSocketHandle safeHandle, WSABUF[] bufarray, SocketFlags flags, out int error)
  2106. {
  2107. bool release = false;
  2108. try {
  2109. safeHandle.DangerousAddRef (ref release);
  2110. return Send_internal (safeHandle.DangerousGetHandle (), bufarray, flags, out error);
  2111. } finally {
  2112. if (release)
  2113. safeHandle.DangerousRelease ();
  2114. }
  2115. }
  2116. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  2117. extern static int Send_internal (IntPtr sock, WSABUF[] bufarray, SocketFlags flags, out int error);
  2118. static int Send_internal (SafeSocketHandle safeHandle, byte[] buf, int offset, int count, SocketFlags flags, out int error)
  2119. {
  2120. try {
  2121. safeHandle.RegisterForBlockingSyscall ();
  2122. return Send_internal (safeHandle.DangerousGetHandle (), buf, offset, count, flags, out error);
  2123. } finally {
  2124. safeHandle.UnRegisterForBlockingSyscall ();
  2125. }
  2126. }
  2127. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2128. extern static int Send_internal(IntPtr sock, byte[] buf, int offset, int count, SocketFlags flags, out int error);
  2129. #endregion
  2130. #region SendTo
  2131. public int SendTo (byte [] buffer, EndPoint remote_end)
  2132. {
  2133. ThrowIfDisposedAndClosed ();
  2134. ThrowIfBufferNull (buffer);
  2135. return SendTo (buffer, 0, buffer.Length, SocketFlags.None, remote_end);
  2136. }
  2137. public int SendTo (byte [] buffer, SocketFlags flags, EndPoint remote_end)
  2138. {
  2139. ThrowIfDisposedAndClosed ();
  2140. ThrowIfBufferNull (buffer);
  2141. return SendTo (buffer, 0, buffer.Length, flags, remote_end);
  2142. }
  2143. public int SendTo (byte [] buffer, int size, SocketFlags flags, EndPoint remote_end)
  2144. {
  2145. return SendTo (buffer, 0, size, flags, remote_end);
  2146. }
  2147. public int SendTo (byte [] buffer, int offset, int size, SocketFlags flags, EndPoint remote_end)
  2148. {
  2149. ThrowIfDisposedAndClosed ();
  2150. ThrowIfBufferNull (buffer);
  2151. ThrowIfBufferOutOfRange (buffer, offset, size);
  2152. if (remote_end == null)
  2153. throw new ArgumentNullException("remote_end");
  2154. return SendTo_nochecks (buffer, offset, size, flags, remote_end);
  2155. }
  2156. public bool SendToAsync (SocketAsyncEventArgs e)
  2157. {
  2158. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  2159. ThrowIfDisposedAndClosed ();
  2160. if (e.BufferList != null)
  2161. throw new NotSupportedException ("Mono doesn't support using BufferList at this point.");
  2162. if (e.RemoteEndPoint == null)
  2163. throw new ArgumentNullException ("remoteEP", "Value cannot be null.");
  2164. InitSocketAsyncEventArgs (e, SendToAsyncCallback, e, SocketOperation.SendTo);
  2165. e.socket_async_result.Buffer = e.Buffer;
  2166. e.socket_async_result.Offset = e.Offset;
  2167. e.socket_async_result.Size = e.Count;
  2168. e.socket_async_result.SockFlags = e.SocketFlags;
  2169. e.socket_async_result.EndPoint = e.RemoteEndPoint;
  2170. QueueIOSelectorJob (writeQ, e.socket_async_result.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), e.socket_async_result));
  2171. return true;
  2172. }
  2173. static AsyncCallback SendToAsyncCallback = new AsyncCallback (ares => {
  2174. SocketAsyncEventArgs e = (SocketAsyncEventArgs) ((SocketAsyncResult) ares).AsyncState;
  2175. if (Interlocked.Exchange (ref e.in_progress, 0) != 1)
  2176. throw new InvalidOperationException ("No operation in progress");
  2177. try {
  2178. e.BytesTransferred = e.current_socket.EndSendTo (ares);
  2179. } catch (SocketException ex) {
  2180. e.SocketError = ex.SocketErrorCode;
  2181. } catch (ObjectDisposedException) {
  2182. e.SocketError = SocketError.OperationAborted;
  2183. } finally {
  2184. e.Complete ();
  2185. }
  2186. });
  2187. public IAsyncResult BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socket_flags, EndPoint remote_end, AsyncCallback callback, object state)
  2188. {
  2189. ThrowIfDisposedAndClosed ();
  2190. ThrowIfBufferNull (buffer);
  2191. ThrowIfBufferOutOfRange (buffer, offset, size);
  2192. SocketAsyncResult sockares = new SocketAsyncResult (this, callback, state, SocketOperation.SendTo) {
  2193. Buffer = buffer,
  2194. Offset = offset,
  2195. Size = size,
  2196. SockFlags = socket_flags,
  2197. EndPoint = remote_end,
  2198. };
  2199. QueueIOSelectorJob (writeQ, sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, 0), sockares));
  2200. return sockares;
  2201. }
  2202. static void BeginSendToCallback (SocketAsyncResult sockares, int sent_so_far)
  2203. {
  2204. int total = 0;
  2205. try {
  2206. total = sockares.socket.SendTo_nochecks (sockares.Buffer, sockares.Offset, sockares.Size, sockares.SockFlags, sockares.EndPoint);
  2207. if (sockares.error == 0) {
  2208. sent_so_far += total;
  2209. sockares.Offset += total;
  2210. sockares.Size -= total;
  2211. }
  2212. if (sockares.Size > 0) {
  2213. IOSelector.Add (sockares.Handle, new IOSelectorJob (IOOperation.Write, s => BeginSendToCallback ((SocketAsyncResult) s, sent_so_far), sockares));
  2214. return; // Have to finish writing everything. See bug #74475.
  2215. }
  2216. sockares.Total = sent_so_far;
  2217. } catch (Exception e) {
  2218. sockares.Complete (e);
  2219. return;
  2220. }
  2221. sockares.Complete ();
  2222. }
  2223. public int EndSendTo (IAsyncResult result)
  2224. {
  2225. ThrowIfDisposedAndClosed ();
  2226. SocketAsyncResult sockares = ValidateEndIAsyncResult (result, "EndSendTo", "result");
  2227. if (!sockares.IsCompleted)
  2228. sockares.AsyncWaitHandle.WaitOne();
  2229. sockares.CheckIfThrowDelayedException();
  2230. return sockares.Total;
  2231. }
  2232. int SendTo_nochecks (byte [] buffer, int offset, int size, SocketFlags flags, EndPoint remote_end)
  2233. {
  2234. int error;
  2235. int ret = SendTo_internal (safe_handle, buffer, offset, size, flags, remote_end.Serialize (), out error);
  2236. SocketError err = (SocketError) error;
  2237. if (err != 0) {
  2238. if (err != SocketError.WouldBlock && err != SocketError.InProgress)
  2239. is_connected = false;
  2240. throw new SocketException (error);
  2241. }
  2242. is_connected = true;
  2243. is_bound = true;
  2244. seed_endpoint = remote_end;
  2245. return ret;
  2246. }
  2247. static int SendTo_internal (SafeSocketHandle safeHandle, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error)
  2248. {
  2249. try {
  2250. safeHandle.RegisterForBlockingSyscall ();
  2251. return SendTo_internal (safeHandle.DangerousGetHandle (), buffer, offset, count, flags, sa, out error);
  2252. } finally {
  2253. safeHandle.UnRegisterForBlockingSyscall ();
  2254. }
  2255. }
  2256. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2257. extern static int SendTo_internal (IntPtr sock, byte[] buffer, int offset, int count, SocketFlags flags, SocketAddress sa, out int error);
  2258. #endregion
  2259. #region SendFile
  2260. public void SendFile (string fileName)
  2261. {
  2262. ThrowIfDisposedAndClosed ();
  2263. if (!is_connected)
  2264. throw new NotSupportedException ();
  2265. if (!is_blocking)
  2266. throw new InvalidOperationException ();
  2267. SendFile (fileName, null, null, 0);
  2268. }
  2269. public void SendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags)
  2270. {
  2271. ThrowIfDisposedAndClosed ();
  2272. if (!is_connected)
  2273. throw new NotSupportedException ();
  2274. if (!is_blocking)
  2275. throw new InvalidOperationException ();
  2276. if (!SendFile_internal (safe_handle, fileName, preBuffer, postBuffer, flags)) {
  2277. SocketException exc = new SocketException ();
  2278. if (exc.ErrorCode == 2 || exc.ErrorCode == 3)
  2279. throw new FileNotFoundException ();
  2280. throw exc;
  2281. }
  2282. }
  2283. public IAsyncResult BeginSendFile (string fileName, 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. return BeginSendFile (fileName, null, null, 0, callback, state);
  2291. }
  2292. public IAsyncResult BeginSendFile (string fileName, byte[] preBuffer, byte[] postBuffer, TransmitFileOptions flags, AsyncCallback callback, object state)
  2293. {
  2294. ThrowIfDisposedAndClosed ();
  2295. if (!is_connected)
  2296. throw new NotSupportedException ();
  2297. if (!File.Exists (fileName))
  2298. throw new FileNotFoundException ();
  2299. SendFileHandler handler = new SendFileHandler (SendFile);
  2300. return new SendFileAsyncResult (handler, handler.BeginInvoke (fileName, preBuffer, postBuffer, flags, ar => callback (new SendFileAsyncResult (handler, ar)), state));
  2301. }
  2302. public void EndSendFile (IAsyncResult asyncResult)
  2303. {
  2304. ThrowIfDisposedAndClosed ();
  2305. if (asyncResult == null)
  2306. throw new ArgumentNullException ("asyncResult");
  2307. SendFileAsyncResult ares = asyncResult as SendFileAsyncResult;
  2308. if (ares == null)
  2309. throw new ArgumentException ("Invalid IAsyncResult", "asyncResult");
  2310. ares.Delegate.EndInvoke (ares.Original);
  2311. }
  2312. static bool SendFile_internal (SafeSocketHandle safeHandle, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags)
  2313. {
  2314. try {
  2315. safeHandle.RegisterForBlockingSyscall ();
  2316. return SendFile_internal (safeHandle.DangerousGetHandle (), filename, pre_buffer, post_buffer, flags);
  2317. } finally {
  2318. safeHandle.UnRegisterForBlockingSyscall ();
  2319. }
  2320. }
  2321. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2322. extern static bool SendFile_internal (IntPtr sock, string filename, byte [] pre_buffer, byte [] post_buffer, TransmitFileOptions flags);
  2323. delegate void SendFileHandler (string fileName, byte [] preBuffer, byte [] postBuffer, TransmitFileOptions flags);
  2324. sealed class SendFileAsyncResult : IAsyncResult {
  2325. IAsyncResult ares;
  2326. SendFileHandler d;
  2327. public SendFileAsyncResult (SendFileHandler d, IAsyncResult ares)
  2328. {
  2329. this.d = d;
  2330. this.ares = ares;
  2331. }
  2332. public object AsyncState {
  2333. get { return ares.AsyncState; }
  2334. }
  2335. public WaitHandle AsyncWaitHandle {
  2336. get { return ares.AsyncWaitHandle; }
  2337. }
  2338. public bool CompletedSynchronously {
  2339. get { return ares.CompletedSynchronously; }
  2340. }
  2341. public bool IsCompleted {
  2342. get { return ares.IsCompleted; }
  2343. }
  2344. public SendFileHandler Delegate {
  2345. get { return d; }
  2346. }
  2347. public IAsyncResult Original {
  2348. get { return ares; }
  2349. }
  2350. }
  2351. #endregion
  2352. #region SendPackets
  2353. [MonoTODO ("Not implemented")]
  2354. public bool SendPacketsAsync (SocketAsyncEventArgs e)
  2355. {
  2356. // NO check is made whether e != null in MS.NET (NRE is thrown in such case)
  2357. ThrowIfDisposedAndClosed ();
  2358. throw new NotImplementedException ();
  2359. }
  2360. #endregion
  2361. #region DuplicateAndClose
  2362. #if !MOBILE
  2363. [MonoLimitation ("We do not support passing sockets across processes, we merely allow this API to pass the socket across AppDomains")]
  2364. public SocketInformation DuplicateAndClose (int targetProcessId)
  2365. {
  2366. var si = new SocketInformation ();
  2367. si.Options =
  2368. (is_listening ? SocketInformationOptions.Listening : 0) |
  2369. (is_connected ? SocketInformationOptions.Connected : 0) |
  2370. (is_blocking ? 0 : SocketInformationOptions.NonBlocking) |
  2371. (use_overlapped_io ? SocketInformationOptions.UseOnlyOverlappedIO : 0);
  2372. si.ProtocolInformation = Mono.DataConverter.Pack ("iiiil", (int)address_family, (int)socket_type, (int)protocol_type, is_bound ? 1 : 0, (long)Handle);
  2373. safe_handle = null;
  2374. return si;
  2375. }
  2376. #endif
  2377. #endregion
  2378. #region GetSocketOption
  2379. public void GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, byte [] optionValue)
  2380. {
  2381. ThrowIfDisposedAndClosed ();
  2382. if (optionValue == null)
  2383. throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");
  2384. int error;
  2385. GetSocketOption_arr_internal (safe_handle, optionLevel, optionName, ref optionValue, out error);
  2386. if (error != 0)
  2387. throw new SocketException (error);
  2388. }
  2389. public byte [] GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int length)
  2390. {
  2391. ThrowIfDisposedAndClosed ();
  2392. int error;
  2393. byte[] byte_val = new byte [length];
  2394. GetSocketOption_arr_internal (safe_handle, optionLevel, optionName, ref byte_val, out error);
  2395. if (error != 0)
  2396. throw new SocketException (error);
  2397. return byte_val;
  2398. }
  2399. public object GetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName)
  2400. {
  2401. ThrowIfDisposedAndClosed ();
  2402. int error;
  2403. object obj_val;
  2404. GetSocketOption_obj_internal (safe_handle, optionLevel, optionName, out obj_val, out error);
  2405. if (error != 0)
  2406. throw new SocketException (error);
  2407. if (optionName == SocketOptionName.Linger)
  2408. return (LingerOption) obj_val;
  2409. else if (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)
  2410. return (MulticastOption) obj_val;
  2411. else if (obj_val is int)
  2412. return (int) obj_val;
  2413. else
  2414. return obj_val;
  2415. }
  2416. static void GetSocketOption_arr_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error)
  2417. {
  2418. bool release = false;
  2419. try {
  2420. safeHandle.DangerousAddRef (ref release);
  2421. GetSocketOption_arr_internal (safeHandle.DangerousGetHandle (), level, name, ref byte_val, out error);
  2422. } finally {
  2423. if (release)
  2424. safeHandle.DangerousRelease ();
  2425. }
  2426. }
  2427. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2428. extern static void GetSocketOption_arr_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error);
  2429. static void GetSocketOption_obj_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error)
  2430. {
  2431. bool release = false;
  2432. try {
  2433. safeHandle.DangerousAddRef (ref release);
  2434. GetSocketOption_obj_internal (safeHandle.DangerousGetHandle (), level, name, out obj_val, out error);
  2435. } finally {
  2436. if (release)
  2437. safeHandle.DangerousRelease ();
  2438. }
  2439. }
  2440. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2441. extern static void GetSocketOption_obj_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error);
  2442. #endregion
  2443. #region SetSocketOption
  2444. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, byte [] optionValue)
  2445. {
  2446. ThrowIfDisposedAndClosed ();
  2447. // I'd throw an ArgumentNullException, but this is what MS does.
  2448. if (optionValue == null)
  2449. throw new SocketException ((int) SocketError.Fault, "Error trying to dereference an invalid pointer");
  2450. int error;
  2451. SetSocketOption_internal (safe_handle, optionLevel, optionName, null, optionValue, 0, out error);
  2452. if (error != 0) {
  2453. if (error == (int) SocketError.InvalidArgument)
  2454. throw new ArgumentException ();
  2455. throw new SocketException (error);
  2456. }
  2457. }
  2458. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue)
  2459. {
  2460. ThrowIfDisposedAndClosed ();
  2461. // NOTE: if a null is passed, the byte[] overload is used instead...
  2462. if (optionValue == null)
  2463. throw new ArgumentNullException("optionValue");
  2464. int error;
  2465. if (optionLevel == SocketOptionLevel.Socket && optionName == SocketOptionName.Linger) {
  2466. LingerOption linger = optionValue as LingerOption;
  2467. if (linger == null)
  2468. throw new ArgumentException ("A 'LingerOption' value must be specified.", "optionValue");
  2469. SetSocketOption_internal (safe_handle, optionLevel, optionName, linger, null, 0, out error);
  2470. } else if (optionLevel == SocketOptionLevel.IP && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
  2471. MulticastOption multicast = optionValue as MulticastOption;
  2472. if (multicast == null)
  2473. throw new ArgumentException ("A 'MulticastOption' value must be specified.", "optionValue");
  2474. SetSocketOption_internal (safe_handle, optionLevel, optionName, multicast, null, 0, out error);
  2475. } else if (optionLevel == SocketOptionLevel.IPv6 && (optionName == SocketOptionName.AddMembership || optionName == SocketOptionName.DropMembership)) {
  2476. IPv6MulticastOption multicast = optionValue as IPv6MulticastOption;
  2477. if (multicast == null)
  2478. throw new ArgumentException ("A 'IPv6MulticastOption' value must be specified.", "optionValue");
  2479. SetSocketOption_internal (safe_handle, optionLevel, optionName, multicast, null, 0, out error);
  2480. } else {
  2481. throw new ArgumentException ("Invalid value specified.", "optionValue");
  2482. }
  2483. if (error != 0) {
  2484. if (error == (int) SocketError.InvalidArgument)
  2485. throw new ArgumentException ();
  2486. throw new SocketException (error);
  2487. }
  2488. }
  2489. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, bool optionValue)
  2490. {
  2491. ThrowIfDisposedAndClosed ();
  2492. int error;
  2493. int int_val = optionValue ? 1 : 0;
  2494. SetSocketOption_internal (safe_handle, optionLevel, optionName, null, null, int_val, out error);
  2495. if (error != 0) {
  2496. if (error == (int) SocketError.InvalidArgument)
  2497. throw new ArgumentException ();
  2498. throw new SocketException (error);
  2499. }
  2500. }
  2501. public void SetSocketOption (SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue)
  2502. {
  2503. ThrowIfDisposedAndClosed ();
  2504. int error;
  2505. SetSocketOption_internal (safe_handle, optionLevel, optionName, null, null, optionValue, out error);
  2506. if (error != 0) {
  2507. throw new SocketException (error);
  2508. }
  2509. }
  2510. static void SetSocketOption_internal (SafeSocketHandle safeHandle, SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error)
  2511. {
  2512. bool release = false;
  2513. try {
  2514. safeHandle.DangerousAddRef (ref release);
  2515. SetSocketOption_internal (safeHandle.DangerousGetHandle (), level, name, obj_val, byte_val, int_val, out error);
  2516. } finally {
  2517. if (release)
  2518. safeHandle.DangerousRelease ();
  2519. }
  2520. }
  2521. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2522. extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level, SocketOptionName name, object obj_val, byte [] byte_val, int int_val, out int error);
  2523. #endregion
  2524. #region IOControl
  2525. public int IOControl (int ioctl_code, byte [] in_value, byte [] out_value)
  2526. {
  2527. if (is_disposed)
  2528. throw new ObjectDisposedException (GetType ().ToString ());
  2529. int error;
  2530. int result = IOControl_internal (safe_handle, ioctl_code, in_value, out_value, out error);
  2531. if (error != 0)
  2532. throw new SocketException (error);
  2533. if (result == -1)
  2534. throw new InvalidOperationException ("Must use Blocking property instead.");
  2535. return result;
  2536. }
  2537. public int IOControl (IOControlCode ioControlCode, byte[] optionInValue, byte[] optionOutValue)
  2538. {
  2539. return IOControl ((int) ioControlCode, optionInValue, optionOutValue);
  2540. }
  2541. static int IOControl_internal (SafeSocketHandle safeHandle, int ioctl_code, byte [] input, byte [] output, out int error)
  2542. {
  2543. bool release = false;
  2544. try {
  2545. safeHandle.DangerousAddRef (ref release);
  2546. return IOControl_internal (safeHandle.DangerousGetHandle (), ioctl_code, input, output, out error);
  2547. } finally {
  2548. if (release)
  2549. safeHandle.DangerousRelease ();
  2550. }
  2551. }
  2552. /* See Socket.IOControl, WSAIoctl documentation in MSDN. The common options between UNIX
  2553. * and Winsock are FIONREAD, FIONBIO and SIOCATMARK. Anything else will depend on the system
  2554. * except SIO_KEEPALIVE_VALS which is properly handled on both windows and linux. */
  2555. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2556. extern static int IOControl_internal (IntPtr sock, int ioctl_code, byte [] input, byte [] output, out int error);
  2557. #endregion
  2558. #region Close
  2559. public void Close ()
  2560. {
  2561. linger_timeout = 0;
  2562. Dispose ();
  2563. }
  2564. public void Close (int timeout)
  2565. {
  2566. linger_timeout = timeout;
  2567. Dispose ();
  2568. }
  2569. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2570. internal extern static void Close_internal (IntPtr socket, out int error);
  2571. #endregion
  2572. #region Shutdown
  2573. public void Shutdown (SocketShutdown how)
  2574. {
  2575. ThrowIfDisposedAndClosed ();
  2576. if (!is_connected)
  2577. throw new SocketException (10057); // Not connected
  2578. int error;
  2579. Shutdown_internal (safe_handle, how, out error);
  2580. if (error != 0)
  2581. throw new SocketException (error);
  2582. }
  2583. static void Shutdown_internal (SafeSocketHandle safeHandle, SocketShutdown how, out int error)
  2584. {
  2585. bool release = false;
  2586. try {
  2587. safeHandle.DangerousAddRef (ref release);
  2588. Shutdown_internal (safeHandle.DangerousGetHandle (), how, out error);
  2589. } finally {
  2590. if (release)
  2591. safeHandle.DangerousRelease ();
  2592. }
  2593. }
  2594. [MethodImplAttribute (MethodImplOptions.InternalCall)]
  2595. internal extern static void Shutdown_internal (IntPtr socket, SocketShutdown how, out int error);
  2596. #endregion
  2597. #region Dispose
  2598. protected virtual void Dispose (bool disposing)
  2599. {
  2600. if (is_disposed)
  2601. return;
  2602. is_disposed = true;
  2603. bool was_connected = is_connected;
  2604. is_connected = false;
  2605. if (safe_handle != null) {
  2606. is_closed = true;
  2607. IntPtr x = Handle;
  2608. if (was_connected)
  2609. Linger (x);
  2610. safe_handle.Dispose ();
  2611. }
  2612. }
  2613. public void Dispose ()
  2614. {
  2615. Dispose (true);
  2616. GC.SuppressFinalize (this);
  2617. }
  2618. void Linger (IntPtr handle)
  2619. {
  2620. if (!is_connected || linger_timeout <= 0)
  2621. return;
  2622. /* We don't want to receive any more data */
  2623. int error;
  2624. Shutdown_internal (handle, SocketShutdown.Receive, out error);
  2625. if (error != 0)
  2626. return;
  2627. int seconds = linger_timeout / 1000;
  2628. int ms = linger_timeout % 1000;
  2629. if (ms > 0) {
  2630. /* If the other end closes, this will return 'true' with 'Available' == 0 */
  2631. Poll_internal (handle, SelectMode.SelectRead, ms * 1000, out error);
  2632. if (error != 0)
  2633. return;
  2634. }
  2635. if (seconds > 0) {
  2636. LingerOption linger = new LingerOption (true, seconds);
  2637. SetSocketOption_internal (handle, SocketOptionLevel.Socket, SocketOptionName.Linger, linger, null, 0, out error);
  2638. /* Not needed, we're closing upon return */
  2639. //if (error != 0)
  2640. // return;
  2641. }
  2642. }
  2643. #endregion
  2644. void ThrowIfDisposedAndClosed (Socket socket)
  2645. {
  2646. if (socket.is_disposed && socket.is_closed)
  2647. throw new ObjectDisposedException (socket.GetType ().ToString ());
  2648. }
  2649. void ThrowIfDisposedAndClosed ()
  2650. {
  2651. if (is_disposed && is_closed)
  2652. throw new ObjectDisposedException (GetType ().ToString ());
  2653. }
  2654. void ThrowIfBufferNull (byte[] buffer)
  2655. {
  2656. if (buffer == null)
  2657. throw new ArgumentNullException ("buffer");
  2658. }
  2659. void ThrowIfBufferOutOfRange (byte[] buffer, int offset, int size)
  2660. {
  2661. if (offset < 0)
  2662. throw new ArgumentOutOfRangeException ("offset", "offset must be >= 0");
  2663. if (offset > buffer.Length)
  2664. throw new ArgumentOutOfRangeException ("offset", "offset must be <= buffer.Length");
  2665. if (size < 0)
  2666. throw new ArgumentOutOfRangeException ("size", "size must be >= 0");
  2667. if (size > buffer.Length - offset)
  2668. throw new ArgumentOutOfRangeException ("size", "size must be <= buffer.Length - offset");
  2669. }
  2670. void ThrowIfUdp ()
  2671. {
  2672. #if !NET_2_1 || MOBILE
  2673. if (protocol_type == ProtocolType.Udp)
  2674. throw new SocketException ((int)SocketError.ProtocolOption);
  2675. #endif
  2676. }
  2677. SocketAsyncResult ValidateEndIAsyncResult (IAsyncResult ares, string methodName, string argName)
  2678. {
  2679. if (ares == null)
  2680. throw new ArgumentNullException (argName);
  2681. SocketAsyncResult sockares = ares as SocketAsyncResult;
  2682. if (sockares == null)
  2683. throw new ArgumentException ("Invalid IAsyncResult", argName);
  2684. if (Interlocked.CompareExchange (ref sockares.EndCalled, 1, 0) == 1)
  2685. throw new InvalidOperationException (methodName + " can only be called once per asynchronous operation");
  2686. return sockares;
  2687. }
  2688. void QueueIOSelectorJob (Queue<KeyValuePair<IntPtr, IOSelectorJob>> queue, IntPtr handle, IOSelectorJob job)
  2689. {
  2690. int count;
  2691. lock (queue) {
  2692. queue.Enqueue (new KeyValuePair<IntPtr, IOSelectorJob> (handle, job));
  2693. count = queue.Count;
  2694. }
  2695. if (count == 1)
  2696. IOSelector.Add (handle, job);
  2697. }
  2698. void InitSocketAsyncEventArgs (SocketAsyncEventArgs e, AsyncCallback callback, object state, SocketOperation operation)
  2699. {
  2700. e.socket_async_result.Init (this, callback, state, operation);
  2701. e.current_socket = this;
  2702. e.SetLastOperation (SocketOperationToSocketAsyncOperation (operation));
  2703. e.SocketError = SocketError.Success;
  2704. e.BytesTransferred = 0;
  2705. }
  2706. SocketAsyncOperation SocketOperationToSocketAsyncOperation (SocketOperation op)
  2707. {
  2708. switch (op) {
  2709. case SocketOperation.Connect:
  2710. return SocketAsyncOperation.Connect;
  2711. case SocketOperation.Accept:
  2712. return SocketAsyncOperation.Accept;
  2713. case SocketOperation.Disconnect:
  2714. return SocketAsyncOperation.Disconnect;
  2715. case SocketOperation.Receive:
  2716. case SocketOperation.ReceiveGeneric:
  2717. return SocketAsyncOperation.Receive;
  2718. case SocketOperation.ReceiveFrom:
  2719. return SocketAsyncOperation.ReceiveFrom;
  2720. case SocketOperation.Send:
  2721. case SocketOperation.SendGeneric:
  2722. return SocketAsyncOperation.Send;
  2723. case SocketOperation.SendTo:
  2724. return SocketAsyncOperation.SendTo;
  2725. default:
  2726. throw new NotImplementedException (String.Format ("Operation {0} is not implemented", op));
  2727. }
  2728. }
  2729. IPEndPoint RemapIPEndPoint (IPEndPoint input) {
  2730. // If socket is DualMode ensure we automatically handle mapping IPv4 addresses to IPv6.
  2731. if (IsDualMode && input.AddressFamily == AddressFamily.InterNetwork)
  2732. return new IPEndPoint (input.Address.MapToIPv6 (), input.Port);
  2733. return input;
  2734. }
  2735. [StructLayout (LayoutKind.Sequential)]
  2736. struct WSABUF {
  2737. public int len;
  2738. public IntPtr buf;
  2739. }
  2740. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2741. internal static extern void cancel_blocking_socket_operation (Thread thread);
  2742. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  2743. internal static extern bool SupportsPortReuse ();
  2744. }
  2745. }