Socket.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937
  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. //
  8. // Copyright (C) 2001, 2002 Phillip Pearson and Ximian, Inc.
  9. // http://www.myelin.co.nz
  10. // (c) 2004 Novell, Inc. (http://www.novell.com)
  11. //
  12. //
  13. // Permission is hereby granted, free of charge, to any person obtaining
  14. // a copy of this software and associated documentation files (the
  15. // "Software"), to deal in the Software without restriction, including
  16. // without limitation the rights to use, copy, modify, merge, publish,
  17. // distribute, sublicense, and/or sell copies of the Software, and to
  18. // permit persons to whom the Software is furnished to do so, subject to
  19. // the following conditions:
  20. //
  21. // The above copyright notice and this permission notice shall be
  22. // included in all copies or substantial portions of the Software.
  23. //
  24. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  25. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  26. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  27. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  28. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  29. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  30. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  31. //
  32. using System;
  33. using System.Net;
  34. using System.Collections;
  35. using System.Runtime.CompilerServices;
  36. using System.Runtime.InteropServices;
  37. using System.Threading;
  38. using System.Reflection;
  39. using System.IO;
  40. using System.Net.Configuration;
  41. namespace System.Net.Sockets
  42. {
  43. public class Socket : IDisposable
  44. {
  45. enum SocketOperation {
  46. Accept,
  47. Connect,
  48. Receive,
  49. ReceiveFrom,
  50. Send,
  51. SendTo
  52. }
  53. [StructLayout (LayoutKind.Sequential)]
  54. private sealed class SocketAsyncResult: IAsyncResult
  55. {
  56. /* Same structure in the runtime */
  57. public Socket Sock;
  58. public IntPtr handle;
  59. object state;
  60. AsyncCallback callback;
  61. WaitHandle waithandle;
  62. Exception delayedException;
  63. public EndPoint EndPoint; // Connect,ReceiveFrom,SendTo
  64. public byte [] Buffer; // Receive,ReceiveFrom,Send,SendTo
  65. public int Offset; // Receive,ReceiveFrom,Send,SendTo
  66. public int Size; // Receive,ReceiveFrom,Send,SendTo
  67. public SocketFlags SockFlags; // Receive,ReceiveFrom,Send,SendTo
  68. // Return values
  69. Socket acc_socket;
  70. int total;
  71. bool completed_sync;
  72. bool completed;
  73. public bool blocking;
  74. internal int error;
  75. SocketOperation operation;
  76. public object ares;
  77. public SocketAsyncResult (Socket sock, object state, AsyncCallback callback, SocketOperation operation)
  78. {
  79. this.Sock = sock;
  80. this.blocking = sock.blocking;
  81. this.handle = sock.socket;
  82. this.state = state;
  83. this.callback = callback;
  84. this.operation = operation;
  85. SockFlags = SocketFlags.None;
  86. }
  87. public void CheckIfThrowDelayedException ()
  88. {
  89. if (delayedException != null)
  90. throw delayedException;
  91. if (error != 0) {
  92. throw new SocketException (error);
  93. }
  94. }
  95. void CompleteAllOnDispose (Queue queue)
  96. {
  97. object [] pending = queue.ToArray ();
  98. queue.Clear ();
  99. WaitCallback cb;
  100. for (int i = 0; i < pending.Length; i++) {
  101. SocketAsyncResult ares = (SocketAsyncResult) pending [i];
  102. cb = new WaitCallback (ares.CompleteDisposed);
  103. ThreadPool.QueueUserWorkItem (cb, null);
  104. }
  105. }
  106. void CompleteDisposed (object unused)
  107. {
  108. Complete ();
  109. }
  110. public void Complete ()
  111. {
  112. if (operation != SocketOperation.Receive && Sock.disposed)
  113. delayedException = new ObjectDisposedException (Sock.GetType ().ToString ());
  114. IsCompleted = true;
  115. Queue queue = null;
  116. if (operation == SocketOperation.Receive || operation == SocketOperation.ReceiveFrom) {
  117. queue = Sock.readQ;
  118. } else if (operation == SocketOperation.Send || operation == SocketOperation.SendTo) {
  119. queue = Sock.writeQ;
  120. }
  121. if (queue != null) {
  122. SocketAsyncCall sac = null;
  123. SocketAsyncResult req = null;
  124. lock (queue) {
  125. queue.Dequeue (); // remove ourselves
  126. if (queue.Count > 0) {
  127. req = (SocketAsyncResult) queue.Peek ();
  128. if (!Sock.disposed) {
  129. Worker worker = new Worker (req);
  130. sac = GetDelegate (worker, req.operation);
  131. } else {
  132. CompleteAllOnDispose (queue);
  133. }
  134. }
  135. }
  136. if (sac != null)
  137. sac.BeginInvoke (null, req);
  138. }
  139. if (callback != null)
  140. callback (this);
  141. }
  142. SocketAsyncCall GetDelegate (Worker worker, SocketOperation op)
  143. {
  144. switch (op) {
  145. case SocketOperation.Receive:
  146. return new SocketAsyncCall (worker.Receive);
  147. case SocketOperation.ReceiveFrom:
  148. return new SocketAsyncCall (worker.ReceiveFrom);
  149. case SocketOperation.Send:
  150. return new SocketAsyncCall (worker.Send);
  151. case SocketOperation.SendTo:
  152. return new SocketAsyncCall (worker.SendTo);
  153. default:
  154. return null; // never happens
  155. }
  156. }
  157. public void Complete (bool synch)
  158. {
  159. completed_sync = synch;
  160. Complete ();
  161. }
  162. public void Complete (int total)
  163. {
  164. this.total = total;
  165. Complete ();
  166. }
  167. public void Complete (Exception e, bool synch)
  168. {
  169. completed_sync = synch;
  170. delayedException = e;
  171. Complete ();
  172. }
  173. public void Complete (Exception e)
  174. {
  175. delayedException = e;
  176. Complete ();
  177. }
  178. public void Complete (Socket s)
  179. {
  180. acc_socket = s;
  181. Complete ();
  182. }
  183. public object AsyncState {
  184. get {
  185. return state;
  186. }
  187. }
  188. public WaitHandle AsyncWaitHandle {
  189. get {
  190. lock (this) {
  191. if (waithandle == null)
  192. waithandle = new ManualResetEvent (completed);
  193. }
  194. return waithandle;
  195. }
  196. set {
  197. waithandle=value;
  198. }
  199. }
  200. public bool CompletedSynchronously {
  201. get {
  202. return(completed_sync);
  203. }
  204. }
  205. public bool IsCompleted {
  206. get {
  207. return(completed);
  208. }
  209. set {
  210. completed=value;
  211. lock (this) {
  212. if (waithandle != null && value) {
  213. ((ManualResetEvent) waithandle).Set ();
  214. }
  215. }
  216. }
  217. }
  218. public Socket Socket {
  219. get {
  220. return acc_socket;
  221. }
  222. }
  223. public int Total {
  224. get { return total; }
  225. set { total = value; }
  226. }
  227. }
  228. private sealed class Worker
  229. {
  230. SocketAsyncResult result;
  231. public Worker (SocketAsyncResult ares)
  232. {
  233. this.result = ares;
  234. }
  235. public void Accept ()
  236. {
  237. Socket acc_socket = null;
  238. try {
  239. acc_socket = result.Sock.Accept ();
  240. } catch (Exception e) {
  241. result.Complete (e);
  242. return;
  243. }
  244. result.Complete (acc_socket);
  245. }
  246. public void Connect ()
  247. {
  248. try {
  249. if (!result.Sock.Blocking) {
  250. result.Sock.Poll (-1, SelectMode.SelectWrite);
  251. int success = (int)result.Sock.GetSocketOption (SocketOptionLevel.Socket, SocketOptionName.Error);
  252. if (success == 0) {
  253. result.Sock.connected = true;
  254. } else {
  255. result.Complete (new SocketException (success));
  256. return;
  257. }
  258. } else {
  259. result.Sock.Connect (result.EndPoint);
  260. result.Sock.connected = true;
  261. }
  262. } catch (Exception e) {
  263. result.Complete (e);
  264. return;
  265. }
  266. result.Complete ();
  267. }
  268. public void Receive ()
  269. {
  270. // Actual recv() done in the runtime
  271. result.Complete ();
  272. }
  273. public void ReceiveFrom ()
  274. {
  275. int total = 0;
  276. try {
  277. total = result.Sock.ReceiveFrom_nochecks (result.Buffer,
  278. result.Offset,
  279. result.Size,
  280. result.SockFlags,
  281. ref result.EndPoint);
  282. } catch (Exception e) {
  283. result.Complete (e);
  284. return;
  285. }
  286. result.Complete (total);
  287. }
  288. int send_so_far;
  289. void UpdateSendValues (int last_sent)
  290. {
  291. if (result.error == 0) {
  292. send_so_far += last_sent;
  293. result.Offset += last_sent;
  294. result.Size -= last_sent;
  295. }
  296. }
  297. public void Send ()
  298. {
  299. // Actual send() done in the runtime
  300. if (result.error == 0) {
  301. UpdateSendValues (result.Total);
  302. if (result.Sock.disposed) {
  303. result.Complete ();
  304. return;
  305. }
  306. if (result.Size > 0) {
  307. SocketAsyncCall sac = new SocketAsyncCall (this.Send);
  308. sac.BeginInvoke (null, result);
  309. return; // Have to finish writing everything. See bug #74475.
  310. }
  311. result.Total = send_so_far;
  312. }
  313. result.Complete ();
  314. }
  315. public void SendTo ()
  316. {
  317. int total = 0;
  318. try {
  319. total = result.Sock.SendTo_nochecks (result.Buffer,
  320. result.Offset,
  321. result.Size,
  322. result.SockFlags,
  323. result.EndPoint);
  324. UpdateSendValues (total);
  325. if (result.Size > 0) {
  326. SocketAsyncCall sac = new SocketAsyncCall (this.SendTo);
  327. sac.BeginInvoke (null, result);
  328. return; // Have to finish writing everything. See bug #74475.
  329. }
  330. result.Total = send_so_far;
  331. } catch (Exception e) {
  332. result.Complete (e);
  333. return;
  334. }
  335. result.Complete ();
  336. }
  337. }
  338. /* the field "socket" is looked up by name by the runtime */
  339. private IntPtr socket;
  340. private AddressFamily address_family;
  341. private SocketType socket_type;
  342. private ProtocolType protocol_type;
  343. internal bool blocking=true;
  344. private Queue readQ = new Queue (2);
  345. private Queue writeQ = new Queue (2);
  346. delegate void SocketAsyncCall ();
  347. /*
  348. * These two fields are looked up by name by the runtime, don't change
  349. * their name without also updating the runtime code.
  350. */
  351. private static int ipv4Supported = -1, ipv6Supported = -1;
  352. /* When true, the socket was connected at the time of
  353. * the last IO operation
  354. */
  355. private bool connected=false;
  356. /* true if we called Close_internal */
  357. private bool closed;
  358. internal bool disposed;
  359. /* Used in LocalEndPoint and RemoteEndPoint if the
  360. * Mono.Posix assembly is available
  361. */
  362. private static object unixendpoint=null;
  363. private static Type unixendpointtype=null;
  364. static void AddSockets (ArrayList sockets, IList list, string name)
  365. {
  366. if (list != null) {
  367. foreach (Socket sock in list) {
  368. if (sock == null) // MS throws a NullRef
  369. throw new ArgumentNullException (name, "Contains a null element");
  370. sockets.Add (sock);
  371. }
  372. }
  373. sockets.Add (null);
  374. }
  375. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  376. private extern static void Select_internal (ref Socket [] sockets,
  377. int microSeconds,
  378. out int error);
  379. public static void Select (IList checkRead, IList checkWrite, IList checkError, int microSeconds)
  380. {
  381. ArrayList list = new ArrayList ();
  382. AddSockets (list, checkRead, "checkRead");
  383. AddSockets (list, checkWrite, "checkWrite");
  384. AddSockets (list, checkError, "checkError");
  385. if (list.Count == 3) {
  386. throw new ArgumentNullException ("checkRead, checkWrite, checkError",
  387. "All the lists are null or empty.");
  388. }
  389. int error;
  390. /*
  391. * The 'sockets' array contains: READ socket 0-n, null,
  392. * WRITE socket 0-n, null,
  393. * ERROR socket 0-n, null
  394. */
  395. Socket [] sockets = (Socket []) list.ToArray (typeof (Socket));
  396. Select_internal (ref sockets, microSeconds, out error);
  397. if (error != 0)
  398. throw new SocketException (error);
  399. if (checkRead != null)
  400. checkRead.Clear ();
  401. if (checkWrite != null)
  402. checkWrite.Clear ();
  403. if (checkError != null)
  404. checkError.Clear ();
  405. if (sockets == null)
  406. return;
  407. int mode = 0;
  408. int count = sockets.Length;
  409. IList currentList = checkRead;
  410. for (int i = 0; i < count; i++) {
  411. Socket sock = sockets [i];
  412. if (sock == null) { // separator
  413. currentList = (mode == 0) ? checkWrite : checkError;
  414. mode++;
  415. continue;
  416. }
  417. if (currentList != null) {
  418. sock.connected = true;
  419. currentList.Add (sock);
  420. }
  421. }
  422. }
  423. static Socket() {
  424. Assembly ass;
  425. try {
  426. ass = Assembly.Load (Consts.AssemblyMono_Posix);
  427. } catch (FileNotFoundException) {
  428. return;
  429. }
  430. unixendpointtype=ass.GetType("Mono.Posix.UnixEndPoint");
  431. /* The endpoint Create() method is an instance
  432. * method :-(
  433. */
  434. Type[] arg_types=new Type[1];
  435. arg_types[0]=typeof(string);
  436. ConstructorInfo cons=unixendpointtype.GetConstructor(arg_types);
  437. object[] args=new object[1];
  438. args[0]="nothing";
  439. unixendpoint=cons.Invoke(args);
  440. }
  441. // private constructor used by Accept, which already
  442. // has a socket handle to use
  443. private Socket(AddressFamily family, SocketType type,
  444. ProtocolType proto, IntPtr sock) {
  445. address_family=family;
  446. socket_type=type;
  447. protocol_type=proto;
  448. socket=sock;
  449. connected=true;
  450. }
  451. // Creates a new system socket, returning the handle
  452. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  453. private extern IntPtr Socket_internal(AddressFamily family,
  454. SocketType type,
  455. ProtocolType proto,
  456. out int error);
  457. public Socket(AddressFamily family, SocketType type,
  458. ProtocolType proto) {
  459. address_family=family;
  460. socket_type=type;
  461. protocol_type=proto;
  462. int error;
  463. socket=Socket_internal(family, type, proto, out error);
  464. if (error != 0) {
  465. throw new SocketException (error);
  466. }
  467. }
  468. public AddressFamily AddressFamily {
  469. get {
  470. return(address_family);
  471. }
  472. }
  473. // Returns the amount of data waiting to be read on socket
  474. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  475. private extern static int Available_internal(IntPtr socket,
  476. out int error);
  477. public int Available {
  478. get {
  479. if (disposed && closed)
  480. throw new ObjectDisposedException (GetType ().ToString ());
  481. int ret, error;
  482. ret = Available_internal(socket, out error);
  483. if (error != 0) {
  484. throw new SocketException (error);
  485. }
  486. return(ret);
  487. }
  488. }
  489. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  490. private extern static void Blocking_internal(IntPtr socket,
  491. bool block,
  492. out int error);
  493. public bool Blocking {
  494. get {
  495. return(blocking);
  496. }
  497. set {
  498. if (disposed && closed)
  499. throw new ObjectDisposedException (GetType ().ToString ());
  500. int error;
  501. Blocking_internal(socket, value, out error);
  502. if (error != 0) {
  503. throw new SocketException (error);
  504. }
  505. blocking=value;
  506. }
  507. }
  508. public bool Connected {
  509. get {
  510. return(connected);
  511. }
  512. }
  513. public IntPtr Handle {
  514. get {
  515. return(socket);
  516. }
  517. }
  518. // Returns the local endpoint details in addr and port
  519. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  520. private extern static SocketAddress LocalEndPoint_internal(IntPtr socket, out int error);
  521. [MonoTODO("Support non-IP endpoints")]
  522. public EndPoint LocalEndPoint {
  523. get {
  524. if (disposed && closed)
  525. throw new ObjectDisposedException (GetType ().ToString ());
  526. SocketAddress sa;
  527. int error;
  528. sa=LocalEndPoint_internal(socket, out error);
  529. if (error != 0) {
  530. throw new SocketException (error);
  531. }
  532. if(sa.Family==AddressFamily.InterNetwork || sa.Family==AddressFamily.InterNetworkV6) {
  533. // Stupidly, EndPoint.Create() is an
  534. // instance method
  535. return new IPEndPoint(0, 0).Create(sa);
  536. } else if (sa.Family==AddressFamily.Unix &&
  537. unixendpoint!=null) {
  538. return((EndPoint)unixendpointtype.InvokeMember("Create", BindingFlags.InvokeMethod|BindingFlags.Instance|BindingFlags.Public, null, unixendpoint, new object[] {sa}));
  539. } else {
  540. throw new NotImplementedException();
  541. }
  542. }
  543. }
  544. public ProtocolType ProtocolType {
  545. get {
  546. return(protocol_type);
  547. }
  548. }
  549. // Returns the remote endpoint details in addr and port
  550. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  551. private extern static SocketAddress RemoteEndPoint_internal(IntPtr socket, out int error);
  552. [MonoTODO("Support non-IP endpoints")]
  553. public EndPoint RemoteEndPoint {
  554. get {
  555. if (disposed && closed)
  556. throw new ObjectDisposedException (GetType ().ToString ());
  557. SocketAddress sa;
  558. int error;
  559. sa=RemoteEndPoint_internal(socket, out error);
  560. if (error != 0) {
  561. throw new SocketException (error);
  562. }
  563. if(sa.Family==AddressFamily.InterNetwork || sa.Family==AddressFamily.InterNetworkV6 ) {
  564. // Stupidly, EndPoint.Create() is an
  565. // instance method
  566. return new IPEndPoint(0, 0).Create(sa);
  567. } else if (sa.Family==AddressFamily.Unix &&
  568. unixendpoint!=null) {
  569. return((EndPoint)unixendpointtype.InvokeMember("Create", BindingFlags.InvokeMethod|BindingFlags.Instance|BindingFlags.Public, null, unixendpoint, new object[] {sa}));
  570. } else {
  571. throw new NotImplementedException();
  572. }
  573. }
  574. }
  575. public SocketType SocketType {
  576. get {
  577. return(socket_type);
  578. }
  579. }
  580. public static bool SupportsIPv4 {
  581. get {
  582. CheckProtocolSupport();
  583. return ipv4Supported == 1;
  584. }
  585. }
  586. public static bool SupportsIPv6 {
  587. get {
  588. CheckProtocolSupport();
  589. return ipv6Supported == 1;
  590. }
  591. }
  592. #if NET_2_0
  593. public int SendTimeout {
  594. get {
  595. return (int)GetSocketOption(
  596. SocketOptionLevel.Socket,
  597. SocketOptionName.SendTimeout);
  598. }
  599. set {
  600. SetSocketOption(
  601. SocketOptionLevel.Socket,
  602. SocketOptionName.SendTimeout, value);
  603. }
  604. }
  605. public int ReceiveTimeout {
  606. get {
  607. return (int)GetSocketOption(
  608. SocketOptionLevel.Socket,
  609. SocketOptionName.ReceiveTimeout);
  610. }
  611. set {
  612. SetSocketOption(
  613. SocketOptionLevel.Socket,
  614. SocketOptionName.ReceiveTimeout, value);
  615. }
  616. }
  617. #endif
  618. internal static void CheckProtocolSupport()
  619. {
  620. if(ipv4Supported == -1) {
  621. try {
  622. Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  623. tmp.Close();
  624. ipv4Supported = 1;
  625. }
  626. catch {
  627. ipv4Supported = 0;
  628. }
  629. }
  630. if(ipv6Supported == -1) {
  631. #if NET_2_0 && CONFIGURATION_DEP
  632. SettingsSection config;
  633. config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
  634. if (config != null)
  635. ipv6Supported = config.Ipv6.Enabled ? -1 : 0;
  636. #else
  637. NetConfig config = (NetConfig)System.Configuration.ConfigurationSettings.GetConfig("system.net/settings");
  638. if(config != null)
  639. ipv6Supported = config.ipv6Enabled?-1:0;
  640. #endif
  641. if(ipv6Supported != 0) {
  642. try {
  643. Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
  644. tmp.Close();
  645. ipv6Supported = 1;
  646. }
  647. catch { }
  648. }
  649. }
  650. }
  651. // Creates a new system socket, returning the handle
  652. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  653. private extern static IntPtr Accept_internal(IntPtr sock,
  654. out int error);
  655. Thread blocking_thread;
  656. public Socket Accept() {
  657. if (disposed && closed)
  658. throw new ObjectDisposedException (GetType ().ToString ());
  659. int error = 0;
  660. IntPtr sock = (IntPtr) (-1);
  661. blocking_thread = Thread.CurrentThread;
  662. try {
  663. sock = Accept_internal(socket, out error);
  664. } catch (ThreadAbortException the) {
  665. if (disposed) {
  666. Thread.ResetAbort ();
  667. error = 10004;
  668. }
  669. } finally {
  670. blocking_thread = null;
  671. }
  672. if (error != 0) {
  673. throw new SocketException (error);
  674. }
  675. Socket accepted = new Socket(this.AddressFamily,
  676. this.SocketType,
  677. this.ProtocolType, sock);
  678. accepted.Blocking = this.Blocking;
  679. return(accepted);
  680. }
  681. public IAsyncResult BeginAccept(AsyncCallback callback,
  682. object state) {
  683. if (disposed && closed)
  684. throw new ObjectDisposedException (GetType ().ToString ());
  685. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Accept);
  686. Worker worker = new Worker (req);
  687. SocketAsyncCall sac = new SocketAsyncCall (worker.Accept);
  688. sac.BeginInvoke (null, req);
  689. return(req);
  690. }
  691. public IAsyncResult BeginConnect(EndPoint end_point,
  692. AsyncCallback callback,
  693. object state) {
  694. if (disposed && closed)
  695. throw new ObjectDisposedException (GetType ().ToString ());
  696. if (end_point == null)
  697. throw new ArgumentNullException ("end_point");
  698. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
  699. req.EndPoint = end_point;
  700. // Bug #75154: Connect() should not succeed for .Any addresses.
  701. if (end_point is IPEndPoint) {
  702. IPEndPoint ep = (IPEndPoint) end_point;
  703. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
  704. req.Complete (new SocketException (10049), true);
  705. return req;
  706. }
  707. }
  708. int error = 0;
  709. if (!blocking) {
  710. SocketAddress serial = end_point.Serialize ();
  711. Connect_internal (socket, serial, out error);
  712. if (error == 0) {
  713. // succeeded synch
  714. connected = true;
  715. req.Complete (true);
  716. } else if (error != 10036 && error != 10035) {
  717. // error synch
  718. connected = false;
  719. req.Complete (new SocketException (error), true);
  720. }
  721. }
  722. if (blocking || error == 10036 || error == 10035) {
  723. // continue asynch
  724. connected = false;
  725. Worker worker = new Worker (req);
  726. SocketAsyncCall sac = new SocketAsyncCall (worker.Connect);
  727. sac.BeginInvoke (null, req);
  728. }
  729. return(req);
  730. }
  731. public IAsyncResult BeginReceive(byte[] buffer, int offset,
  732. int size,
  733. SocketFlags socket_flags,
  734. AsyncCallback callback,
  735. object state) {
  736. if (disposed && closed)
  737. throw new ObjectDisposedException (GetType ().ToString ());
  738. if (buffer == null)
  739. throw new ArgumentNullException ("buffer");
  740. if (offset < 0 || offset > buffer.Length)
  741. throw new ArgumentOutOfRangeException ("offset");
  742. if (size < 0 || offset + size > buffer.Length)
  743. throw new ArgumentOutOfRangeException ("size");
  744. SocketAsyncResult req;
  745. lock (readQ) {
  746. req = new SocketAsyncResult (this, state, callback, SocketOperation.Receive);
  747. req.Buffer = buffer;
  748. req.Offset = offset;
  749. req.Size = size;
  750. req.SockFlags = socket_flags;
  751. readQ.Enqueue (req);
  752. if (readQ.Count == 1) {
  753. Worker worker = new Worker (req);
  754. SocketAsyncCall sac = new SocketAsyncCall (worker.Receive);
  755. sac.BeginInvoke (null, req);
  756. }
  757. }
  758. return req;
  759. }
  760. public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset,
  761. int size,
  762. SocketFlags socket_flags,
  763. ref EndPoint remote_end,
  764. AsyncCallback callback,
  765. object state) {
  766. if (disposed && closed)
  767. throw new ObjectDisposedException (GetType ().ToString ());
  768. if (buffer == null)
  769. throw new ArgumentNullException ("buffer");
  770. if (offset < 0)
  771. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  772. if (size < 0)
  773. throw new ArgumentOutOfRangeException ("size must be >= 0");
  774. if (offset + size > buffer.Length)
  775. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  776. SocketAsyncResult req;
  777. lock (readQ) {
  778. req = new SocketAsyncResult (this, state, callback, SocketOperation.ReceiveFrom);
  779. req.Buffer = buffer;
  780. req.Offset = offset;
  781. req.Size = size;
  782. req.SockFlags = socket_flags;
  783. req.EndPoint = remote_end;
  784. readQ.Enqueue (req);
  785. if (readQ.Count == 1) {
  786. Worker worker = new Worker (req);
  787. SocketAsyncCall sac = new SocketAsyncCall (worker.ReceiveFrom);
  788. sac.BeginInvoke (null, req);
  789. }
  790. }
  791. return req;
  792. }
  793. public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socket_flags,
  794. AsyncCallback callback, object state)
  795. {
  796. if (disposed && closed)
  797. throw new ObjectDisposedException (GetType ().ToString ());
  798. if (buffer == null)
  799. throw new ArgumentNullException ("buffer");
  800. if (offset < 0)
  801. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  802. if (size < 0)
  803. throw new ArgumentOutOfRangeException ("size must be >= 0");
  804. if (offset + size > buffer.Length)
  805. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  806. SocketAsyncResult req;
  807. lock (writeQ) {
  808. req = new SocketAsyncResult (this, state, callback, SocketOperation.Send);
  809. req.Buffer = buffer;
  810. req.Offset = offset;
  811. req.Size = size;
  812. req.SockFlags = socket_flags;
  813. writeQ.Enqueue (req);
  814. if (writeQ.Count == 1) {
  815. Worker worker = new Worker (req);
  816. SocketAsyncCall sac = new SocketAsyncCall (worker.Send);
  817. sac.BeginInvoke (null, req);
  818. }
  819. }
  820. return req;
  821. }
  822. public IAsyncResult BeginSendTo(byte[] buffer, int offset,
  823. int size,
  824. SocketFlags socket_flags,
  825. EndPoint remote_end,
  826. AsyncCallback callback,
  827. object state) {
  828. if (disposed && closed)
  829. throw new ObjectDisposedException (GetType ().ToString ());
  830. if (buffer == null)
  831. throw new ArgumentNullException ("buffer");
  832. if (offset < 0)
  833. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  834. if (size < 0)
  835. throw new ArgumentOutOfRangeException ("size must be >= 0");
  836. if (offset + size > buffer.Length)
  837. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  838. SocketAsyncResult req;
  839. lock (writeQ) {
  840. req = new SocketAsyncResult (this, state, callback, SocketOperation.SendTo);
  841. req.Buffer = buffer;
  842. req.Offset = offset;
  843. req.Size = size;
  844. req.SockFlags = socket_flags;
  845. req.EndPoint = remote_end;
  846. writeQ.Enqueue (req);
  847. if (writeQ.Count == 1) {
  848. Worker worker = new Worker (req);
  849. SocketAsyncCall sac = new SocketAsyncCall (worker.SendTo);
  850. sac.BeginInvoke (null, req);
  851. }
  852. }
  853. return req;
  854. }
  855. // Creates a new system socket, returning the handle
  856. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  857. private extern static void Bind_internal(IntPtr sock,
  858. SocketAddress sa,
  859. out int error);
  860. public void Bind(EndPoint local_end) {
  861. if (disposed && closed)
  862. throw new ObjectDisposedException (GetType ().ToString ());
  863. if(local_end==null) {
  864. throw new ArgumentNullException("local_end");
  865. }
  866. int error;
  867. Bind_internal(socket, local_end.Serialize(),
  868. out error);
  869. if (error != 0) {
  870. throw new SocketException (error);
  871. }
  872. }
  873. // Closes the socket
  874. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  875. private extern static void Close_internal(IntPtr socket,
  876. out int error);
  877. public void Close() {
  878. ((IDisposable) this).Dispose ();
  879. }
  880. // Connects to the remote address
  881. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  882. private extern static void Connect_internal(IntPtr sock,
  883. SocketAddress sa,
  884. out int error);
  885. public void Connect(EndPoint remote_end) {
  886. if (disposed && closed)
  887. throw new ObjectDisposedException (GetType ().ToString ());
  888. if(remote_end==null) {
  889. throw new ArgumentNullException("remote_end");
  890. }
  891. if (remote_end is IPEndPoint) {
  892. IPEndPoint ep = (IPEndPoint) remote_end;
  893. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
  894. throw new SocketException (10049);
  895. }
  896. SocketAddress serial = remote_end.Serialize ();
  897. int error = 0;
  898. blocking_thread = Thread.CurrentThread;
  899. try {
  900. Connect_internal (socket, serial, out error);
  901. } catch (ThreadAbortException the) {
  902. if (disposed) {
  903. Thread.ResetAbort ();
  904. error = 10004;
  905. }
  906. } finally {
  907. blocking_thread = null;
  908. }
  909. if (error != 0) {
  910. throw new SocketException (error);
  911. }
  912. connected=true;
  913. }
  914. public Socket EndAccept(IAsyncResult result) {
  915. if (disposed && closed)
  916. throw new ObjectDisposedException (GetType ().ToString ());
  917. if (result == null)
  918. throw new ArgumentNullException ("result");
  919. SocketAsyncResult req = result as SocketAsyncResult;
  920. if (req == null)
  921. throw new ArgumentException ("Invalid IAsyncResult", "result");
  922. if (!result.IsCompleted)
  923. result.AsyncWaitHandle.WaitOne();
  924. req.CheckIfThrowDelayedException();
  925. return req.Socket;
  926. }
  927. public void EndConnect(IAsyncResult result) {
  928. if (disposed && closed)
  929. throw new ObjectDisposedException (GetType ().ToString ());
  930. if (result == null)
  931. throw new ArgumentNullException ("result");
  932. SocketAsyncResult req = result as SocketAsyncResult;
  933. if (req == null)
  934. throw new ArgumentException ("Invalid IAsyncResult", "result");
  935. if (!result.IsCompleted)
  936. result.AsyncWaitHandle.WaitOne();
  937. req.CheckIfThrowDelayedException();
  938. }
  939. public int EndReceive(IAsyncResult result) {
  940. if (disposed && closed)
  941. throw new ObjectDisposedException (GetType ().ToString ());
  942. if (result == null)
  943. throw new ArgumentNullException ("result");
  944. SocketAsyncResult req = result as SocketAsyncResult;
  945. if (req == null)
  946. throw new ArgumentException ("Invalid IAsyncResult", "result");
  947. if (!result.IsCompleted)
  948. result.AsyncWaitHandle.WaitOne();
  949. req.CheckIfThrowDelayedException();
  950. return req.Total;
  951. }
  952. public int EndReceiveFrom(IAsyncResult result,
  953. ref EndPoint end_point) {
  954. if (disposed && closed)
  955. throw new ObjectDisposedException (GetType ().ToString ());
  956. if (result == null)
  957. throw new ArgumentNullException ("result");
  958. SocketAsyncResult req = result as SocketAsyncResult;
  959. if (req == null)
  960. throw new ArgumentException ("Invalid IAsyncResult", "result");
  961. if (!result.IsCompleted)
  962. result.AsyncWaitHandle.WaitOne();
  963. req.CheckIfThrowDelayedException();
  964. end_point = req.EndPoint;
  965. return req.Total;
  966. }
  967. public int EndSend(IAsyncResult result) {
  968. if (disposed && closed)
  969. throw new ObjectDisposedException (GetType ().ToString ());
  970. if (result == null)
  971. throw new ArgumentNullException ("result");
  972. SocketAsyncResult req = result as SocketAsyncResult;
  973. if (req == null)
  974. throw new ArgumentException ("Invalid IAsyncResult", "result");
  975. if (!result.IsCompleted)
  976. result.AsyncWaitHandle.WaitOne();
  977. req.CheckIfThrowDelayedException();
  978. return req.Total;
  979. }
  980. public int EndSendTo(IAsyncResult result) {
  981. if (disposed && closed)
  982. throw new ObjectDisposedException (GetType ().ToString ());
  983. if (result == null)
  984. throw new ArgumentNullException ("result");
  985. SocketAsyncResult req = result as SocketAsyncResult;
  986. if (req == null)
  987. throw new ArgumentException ("Invalid IAsyncResult", "result");
  988. if (!result.IsCompleted)
  989. result.AsyncWaitHandle.WaitOne();
  990. req.CheckIfThrowDelayedException();
  991. return req.Total;
  992. }
  993. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  994. private extern static void GetSocketOption_obj_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error);
  995. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  996. private extern static void GetSocketOption_arr_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error);
  997. public object GetSocketOption (SocketOptionLevel level, SocketOptionName name)
  998. {
  999. if (disposed && closed)
  1000. throw new ObjectDisposedException (GetType ().ToString ());
  1001. object obj_val;
  1002. int error;
  1003. GetSocketOption_obj_internal(socket, level, name,
  1004. out obj_val, out error);
  1005. if (error != 0) {
  1006. throw new SocketException (error);
  1007. }
  1008. if(name==SocketOptionName.Linger) {
  1009. return((LingerOption)obj_val);
  1010. } else if (name==SocketOptionName.AddMembership ||
  1011. name==SocketOptionName.DropMembership) {
  1012. return((MulticastOption)obj_val);
  1013. } else if (obj_val is int) {
  1014. return((int)obj_val);
  1015. } else {
  1016. return(obj_val);
  1017. }
  1018. }
  1019. public void GetSocketOption (SocketOptionLevel level, SocketOptionName name, byte [] opt_value)
  1020. {
  1021. if (disposed && closed)
  1022. throw new ObjectDisposedException (GetType ().ToString ());
  1023. int error;
  1024. GetSocketOption_arr_internal(socket, level, name,
  1025. ref opt_value, out error);
  1026. if (error != 0) {
  1027. throw new SocketException (error);
  1028. }
  1029. }
  1030. public byte [] GetSocketOption (SocketOptionLevel level, SocketOptionName name, int length)
  1031. {
  1032. if (disposed && closed)
  1033. throw new ObjectDisposedException (GetType ().ToString ());
  1034. byte[] byte_val=new byte[length];
  1035. int error;
  1036. GetSocketOption_arr_internal(socket, level, name,
  1037. ref byte_val, out error);
  1038. if (error != 0) {
  1039. throw new SocketException (error);
  1040. }
  1041. return(byte_val);
  1042. }
  1043. // See Socket.IOControl, WSAIoctl documentation in MSDN. The
  1044. // common options between UNIX and Winsock are FIONREAD,
  1045. // FIONBIO and SIOCATMARK. Anything else will depend on the
  1046. // system.
  1047. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1048. extern static int WSAIoctl (IntPtr sock, int ioctl_code,
  1049. byte [] input, byte [] output,
  1050. out int error);
  1051. public int IOControl (int ioctl_code, byte [] in_value, byte [] out_value)
  1052. {
  1053. if (disposed)
  1054. throw new ObjectDisposedException (GetType ().ToString ());
  1055. int error;
  1056. int result = WSAIoctl (socket, ioctl_code, in_value,
  1057. out_value, out error);
  1058. if (error != 0) {
  1059. throw new SocketException (error);
  1060. }
  1061. if (result == -1)
  1062. throw new InvalidOperationException ("Must use Blocking property instead.");
  1063. return result;
  1064. }
  1065. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1066. private extern static void Listen_internal(IntPtr sock,
  1067. int backlog,
  1068. out int error);
  1069. public void Listen (int backlog)
  1070. {
  1071. if (disposed && closed)
  1072. throw new ObjectDisposedException (GetType ().ToString ());
  1073. int error;
  1074. Listen_internal(socket, backlog, out error);
  1075. if (error != 0) {
  1076. throw new SocketException (error);
  1077. }
  1078. }
  1079. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1080. extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
  1081. public bool Poll (int time_us, SelectMode mode)
  1082. {
  1083. if (disposed && closed)
  1084. throw new ObjectDisposedException (GetType ().ToString ());
  1085. if (mode != SelectMode.SelectRead &&
  1086. mode != SelectMode.SelectWrite &&
  1087. mode != SelectMode.SelectError)
  1088. throw new NotSupportedException ("'mode' parameter is not valid.");
  1089. int error;
  1090. bool result = Poll_internal (socket, mode, time_us, out error);
  1091. if (error != 0)
  1092. throw new SocketException (error);
  1093. if (result == true) {
  1094. /* Update the connected state; for
  1095. * non-blocking Connect()s this is
  1096. * when we can find out that the
  1097. * connect succeeded.
  1098. */
  1099. connected = true;
  1100. }
  1101. return result;
  1102. }
  1103. public int Receive (byte [] buf)
  1104. {
  1105. if (disposed && closed)
  1106. throw new ObjectDisposedException (GetType ().ToString ());
  1107. if (buf == null)
  1108. throw new ArgumentNullException ("buf");
  1109. SocketError error;
  1110. int ret = Receive_nochecks (buf, 0, buf.Length, SocketFlags.None, out error);
  1111. if (error != SocketError.Success)
  1112. throw new SocketException ((int) error);
  1113. return ret;
  1114. }
  1115. public int Receive (byte [] buf, SocketFlags flags)
  1116. {
  1117. if (disposed && closed)
  1118. throw new ObjectDisposedException (GetType ().ToString ());
  1119. if (buf == null)
  1120. throw new ArgumentNullException ("buf");
  1121. SocketError error;
  1122. int ret = Receive_nochecks (buf, 0, buf.Length, flags, out error);
  1123. if (error != SocketError.Success)
  1124. throw new SocketException ((int) error);
  1125. return ret;
  1126. }
  1127. public int Receive (byte [] buf, int size, SocketFlags flags)
  1128. {
  1129. if (disposed && closed)
  1130. throw new ObjectDisposedException (GetType ().ToString ());
  1131. if (buf == null)
  1132. throw new ArgumentNullException ("buf");
  1133. if (size < 0 || size > buf.Length)
  1134. throw new ArgumentOutOfRangeException ("size");
  1135. SocketError error;
  1136. int ret = Receive_nochecks (buf, 0, size, flags, out error);
  1137. if (error != SocketError.Success)
  1138. throw new SocketException ((int) error);
  1139. return ret;
  1140. }
  1141. public int Receive (byte [] buf, int offset, int size, SocketFlags flags)
  1142. {
  1143. if (disposed && closed)
  1144. throw new ObjectDisposedException (GetType ().ToString ());
  1145. if (buf == null)
  1146. throw new ArgumentNullException ("buf");
  1147. if (offset < 0 || offset > buf.Length)
  1148. throw new ArgumentOutOfRangeException ("offset");
  1149. if (size < 0 || offset + size > buf.Length)
  1150. throw new ArgumentOutOfRangeException ("size");
  1151. SocketError error;
  1152. int ret = Receive_nochecks (buf, offset, size, flags, out error);
  1153. if(error != SocketError.Success)
  1154. throw new SocketException ((int) error);
  1155. return ret;
  1156. }
  1157. #if NET_2_0
  1158. public int Receive (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  1159. {
  1160. if (disposed && closed)
  1161. throw new ObjectDisposedException (GetType ().ToString ());
  1162. if (buf == null)
  1163. throw new ArgumentNullException ("buf");
  1164. if (offset < 0 || offset > buf.Length)
  1165. throw new ArgumentOutOfRangeException ("offset");
  1166. if (size < 0 || offset + size > buf.Length)
  1167. throw new ArgumentOutOfRangeException ("size");
  1168. return Receive_nochecks (buf, offset, size, flags, out error);
  1169. }
  1170. #endif
  1171. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1172. private extern static int Receive_internal(IntPtr sock,
  1173. byte[] buffer,
  1174. int offset,
  1175. int count,
  1176. SocketFlags flags,
  1177. out int error);
  1178. int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  1179. {
  1180. int nativeError;
  1181. int ret = Receive_internal (socket, buf, offset, size, flags, out nativeError);
  1182. error = (SocketError) nativeError;
  1183. if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress)
  1184. connected = false;
  1185. else
  1186. connected = true;
  1187. return ret;
  1188. }
  1189. public int ReceiveFrom (byte [] buf, ref EndPoint remote_end)
  1190. {
  1191. if (disposed && closed)
  1192. throw new ObjectDisposedException (GetType ().ToString ());
  1193. if (buf == null)
  1194. throw new ArgumentNullException ("buf");
  1195. if (remote_end == null)
  1196. throw new ArgumentNullException ("remote_end");
  1197. return ReceiveFrom_nochecks (buf, 0, buf.Length, SocketFlags.None, ref remote_end);
  1198. }
  1199. public int ReceiveFrom (byte [] buf, SocketFlags flags, ref EndPoint remote_end)
  1200. {
  1201. if (disposed && closed)
  1202. throw new ObjectDisposedException (GetType ().ToString ());
  1203. if (buf == null)
  1204. throw new ArgumentNullException ("buf");
  1205. if (remote_end == null)
  1206. throw new ArgumentNullException ("remote_end");
  1207. return ReceiveFrom_nochecks (buf, 0, buf.Length, flags, ref remote_end);
  1208. }
  1209. public int ReceiveFrom (byte [] buf, int size, SocketFlags flags,
  1210. ref EndPoint remote_end)
  1211. {
  1212. if (disposed && closed)
  1213. throw new ObjectDisposedException (GetType ().ToString ());
  1214. if (buf == null)
  1215. throw new ArgumentNullException ("buf");
  1216. if (remote_end == null)
  1217. throw new ArgumentNullException ("remote_end");
  1218. if (size < 0 || size > buf.Length)
  1219. throw new ArgumentOutOfRangeException ("size");
  1220. return ReceiveFrom_nochecks (buf, 0, size, flags, ref remote_end);
  1221. }
  1222. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1223. private extern static int RecvFrom_internal(IntPtr sock,
  1224. byte[] buffer,
  1225. int offset,
  1226. int count,
  1227. SocketFlags flags,
  1228. ref SocketAddress sockaddr,
  1229. out int error);
  1230. public int ReceiveFrom (byte [] buf, int offset, int size, SocketFlags flags,
  1231. ref EndPoint remote_end)
  1232. {
  1233. if (disposed && closed)
  1234. throw new ObjectDisposedException (GetType ().ToString ());
  1235. if (buf == null)
  1236. throw new ArgumentNullException ("buf");
  1237. if (remote_end == null)
  1238. throw new ArgumentNullException ("remote_end");
  1239. if (offset < 0 || offset > buf.Length)
  1240. throw new ArgumentOutOfRangeException ("offset");
  1241. if (size < 0 || offset + size > buf.Length)
  1242. throw new ArgumentOutOfRangeException ("size");
  1243. return ReceiveFrom_nochecks (buf, offset, size, flags, ref remote_end);
  1244. }
  1245. int ReceiveFrom_nochecks (byte [] buf, int offset, int size, SocketFlags flags,
  1246. ref EndPoint remote_end)
  1247. {
  1248. SocketAddress sockaddr = remote_end.Serialize();
  1249. int cnt, error;
  1250. cnt = RecvFrom_internal (socket, buf, offset, size, flags, ref sockaddr, out error);
  1251. if (error != 0) {
  1252. if (error != 10035 && error != 10036) // WSAEWOULDBLOCK && WSAEINPROGRESS
  1253. connected = false;
  1254. throw new SocketException (error);
  1255. }
  1256. connected = true;
  1257. // If sockaddr is null then we're a connection
  1258. // oriented protocol and should ignore the
  1259. // remote_end parameter (see MSDN
  1260. // documentation for Socket.ReceiveFrom(...) )
  1261. if ( sockaddr != null ) {
  1262. // Stupidly, EndPoint.Create() is an
  1263. // instance method
  1264. remote_end = remote_end.Create (sockaddr);
  1265. }
  1266. return cnt;
  1267. }
  1268. public int Send (byte [] buf)
  1269. {
  1270. if (disposed && closed)
  1271. throw new ObjectDisposedException (GetType ().ToString ());
  1272. if (buf == null)
  1273. throw new ArgumentNullException ("buf");
  1274. SocketError error;
  1275. int ret = Send_nochecks (buf, 0, buf.Length, SocketFlags.None, out error);
  1276. if (error != SocketError.Success)
  1277. throw new SocketException ((int) error);
  1278. return ret;
  1279. }
  1280. public int Send (byte [] buf, SocketFlags flags)
  1281. {
  1282. if (disposed && closed)
  1283. throw new ObjectDisposedException (GetType ().ToString ());
  1284. if (buf == null)
  1285. throw new ArgumentNullException ("buf");
  1286. SocketError error;
  1287. int ret = Send_nochecks (buf, 0, buf.Length, flags, out error);
  1288. if (error != SocketError.Success)
  1289. throw new SocketException ((int) error);
  1290. return ret;
  1291. }
  1292. public int Send (byte [] buf, int size, SocketFlags flags)
  1293. {
  1294. if (disposed && closed)
  1295. throw new ObjectDisposedException (GetType ().ToString ());
  1296. if (buf == null)
  1297. throw new ArgumentNullException ("buf");
  1298. if (size < 0 || size > buf.Length)
  1299. throw new ArgumentOutOfRangeException ("size");
  1300. SocketError error;
  1301. int ret = Send_nochecks (buf, 0, size, flags, out error);
  1302. if (error != SocketError.Success)
  1303. throw new SocketException ((int) error);
  1304. return ret;
  1305. }
  1306. public int Send (byte [] buf, int offset, int size, SocketFlags flags)
  1307. {
  1308. if (disposed && closed)
  1309. throw new ObjectDisposedException (GetType ().ToString ());
  1310. if (buf == null)
  1311. throw new ArgumentNullException ("buffer");
  1312. if (offset < 0 || offset > buf.Length)
  1313. throw new ArgumentOutOfRangeException ("offset");
  1314. if (size < 0 || offset + size > buf.Length)
  1315. throw new ArgumentOutOfRangeException ("size");
  1316. SocketError error;
  1317. int ret = Send_nochecks (buf, offset, size, flags, out error);
  1318. if (error != SocketError.Success)
  1319. throw new SocketException ((int) error);
  1320. return ret;
  1321. }
  1322. #if NET_2_0
  1323. public int Send (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  1324. {
  1325. if (disposed && closed)
  1326. throw new ObjectDisposedException (GetType ().ToString ());
  1327. if (buf == null)
  1328. throw new ArgumentNullException ("buffer");
  1329. if (offset < 0 || offset > buf.Length)
  1330. throw new ArgumentOutOfRangeException ("offset");
  1331. if (size < 0 || offset + size > buf.Length)
  1332. throw new ArgumentOutOfRangeException ("size");
  1333. return Send_nochecks (buf, offset, size, flags, out error);
  1334. }
  1335. #endif
  1336. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1337. private extern static int Send_internal(IntPtr sock,
  1338. byte[] buf, int offset,
  1339. int count,
  1340. SocketFlags flags,
  1341. out int error);
  1342. int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  1343. {
  1344. if (size == 0) {
  1345. error = SocketError.Success;
  1346. return 0;
  1347. }
  1348. int nativeError;
  1349. int ret = Send_internal (socket, buf, offset, size, flags, out nativeError);
  1350. error = (SocketError)nativeError;
  1351. if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress)
  1352. connected = false;
  1353. else
  1354. connected = true;
  1355. return ret;
  1356. }
  1357. public int SendTo (byte [] buffer, EndPoint remote_end)
  1358. {
  1359. if (disposed && closed)
  1360. throw new ObjectDisposedException (GetType ().ToString ());
  1361. if (buffer == null)
  1362. throw new ArgumentNullException ("buffer");
  1363. if (remote_end == null)
  1364. throw new ArgumentNullException ("remote_end");
  1365. return SendTo_nochecks (buffer, 0, buffer.Length, SocketFlags.None, remote_end);
  1366. }
  1367. public int SendTo (byte [] buffer, SocketFlags flags, EndPoint remote_end)
  1368. {
  1369. if (disposed && closed)
  1370. throw new ObjectDisposedException (GetType ().ToString ());
  1371. if (buffer == null)
  1372. throw new ArgumentNullException ("buffer");
  1373. if (remote_end == null)
  1374. throw new ArgumentNullException ("remote_end");
  1375. return SendTo_nochecks (buffer, 0, buffer.Length, flags, remote_end);
  1376. }
  1377. public int SendTo (byte [] buffer, int size, SocketFlags flags, EndPoint remote_end)
  1378. {
  1379. if (disposed && closed)
  1380. throw new ObjectDisposedException (GetType ().ToString ());
  1381. if (buffer == null)
  1382. throw new ArgumentNullException ("buffer");
  1383. if (remote_end == null)
  1384. throw new ArgumentNullException ("remote_end");
  1385. if (size < 0 || size > buffer.Length)
  1386. throw new ArgumentOutOfRangeException ("size");
  1387. return SendTo_nochecks (buffer, 0, size, flags, remote_end);
  1388. }
  1389. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1390. private extern static int SendTo_internal(IntPtr sock,
  1391. byte[] buffer,
  1392. int offset,
  1393. int count,
  1394. SocketFlags flags,
  1395. SocketAddress sa,
  1396. out int error);
  1397. public int SendTo (byte [] buffer, int offset, int size, SocketFlags flags,
  1398. EndPoint remote_end)
  1399. {
  1400. if (disposed && closed)
  1401. throw new ObjectDisposedException (GetType ().ToString ());
  1402. if (buffer == null)
  1403. throw new ArgumentNullException ("buffer");
  1404. if (remote_end == null)
  1405. throw new ArgumentNullException("remote_end");
  1406. if (offset < 0 || offset > buffer.Length)
  1407. throw new ArgumentOutOfRangeException ("offset");
  1408. if (size < 0 || offset + size > buffer.Length)
  1409. throw new ArgumentOutOfRangeException ("size");
  1410. return SendTo_nochecks (buffer, offset, size, flags, remote_end);
  1411. }
  1412. int SendTo_nochecks (byte [] buffer, int offset, int size, SocketFlags flags,
  1413. EndPoint remote_end)
  1414. {
  1415. SocketAddress sockaddr = remote_end.Serialize ();
  1416. int ret, error;
  1417. ret = SendTo_internal (socket, buffer, offset, size, flags, sockaddr, out error);
  1418. if (error != 0) {
  1419. if (error != 10035 && error != 10036) // WSAEWOULDBLOCK && WSAEINPROGRESS
  1420. connected = false;
  1421. throw new SocketException (error);
  1422. }
  1423. connected = true;
  1424. return ret;
  1425. }
  1426. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1427. private extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level,
  1428. SocketOptionName name, object obj_val,
  1429. byte [] byte_val, int int_val,
  1430. out int error);
  1431. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, byte[] opt_value)
  1432. {
  1433. if (disposed && closed)
  1434. throw new ObjectDisposedException (GetType ().ToString ());
  1435. int error;
  1436. SetSocketOption_internal(socket, level, name, null,
  1437. opt_value, 0, out error);
  1438. if (error != 0) {
  1439. throw new SocketException (error);
  1440. }
  1441. }
  1442. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, int opt_value)
  1443. {
  1444. if (disposed && closed)
  1445. throw new ObjectDisposedException (GetType ().ToString ());
  1446. int error;
  1447. SetSocketOption_internal(socket, level, name, null,
  1448. null, opt_value, out error);
  1449. if (error != 0) {
  1450. throw new SocketException (error);
  1451. }
  1452. }
  1453. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, object opt_value)
  1454. {
  1455. if (disposed && closed)
  1456. throw new ObjectDisposedException (GetType ().ToString ());
  1457. if(opt_value==null) {
  1458. throw new ArgumentNullException();
  1459. }
  1460. int error;
  1461. /* From MS documentation on SetSocketOption: "For an
  1462. * option with a Boolean data type, specify a nonzero
  1463. * value to enable the option, and a zero value to
  1464. * disable the option."
  1465. * Booleans are only handled in 2.0
  1466. */
  1467. if (opt_value is System.Boolean) {
  1468. #if NET_2_0
  1469. bool bool_val = (bool) opt_value;
  1470. int int_val = (bool_val) ? 1 : 0;
  1471. SetSocketOption_internal (socket, level, name, null, null, int_val, out error);
  1472. #else
  1473. throw new ArgumentException ("Use an integer 1 (true) or 0 (false) instead of a boolean.", "opt_value");
  1474. #endif
  1475. } else {
  1476. SetSocketOption_internal (socket, level, name, opt_value, null, 0, out error);
  1477. }
  1478. if (error != 0)
  1479. throw new SocketException (error);
  1480. }
  1481. #if NET_2_0
  1482. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, bool optionValue)
  1483. {
  1484. if (disposed && closed)
  1485. throw new ObjectDisposedException (GetType ().ToString ());
  1486. int error;
  1487. int int_val = (optionValue) ? 1 : 0;
  1488. SetSocketOption_internal (socket, level, name, null, null, int_val, out error);
  1489. if (error != 0)
  1490. throw new SocketException (error);
  1491. }
  1492. #endif
  1493. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1494. private extern static void Shutdown_internal(IntPtr socket, SocketShutdown how, out int error);
  1495. public void Shutdown (SocketShutdown how)
  1496. {
  1497. if (disposed && closed)
  1498. throw new ObjectDisposedException (GetType ().ToString ());
  1499. int error;
  1500. Shutdown_internal(socket, how, out error);
  1501. if (error != 0) {
  1502. throw new SocketException (error);
  1503. }
  1504. }
  1505. public override int GetHashCode ()
  1506. {
  1507. return (int) socket;
  1508. }
  1509. protected virtual void Dispose (bool explicitDisposing)
  1510. {
  1511. if (disposed)
  1512. return;
  1513. disposed = true;
  1514. connected = false;
  1515. if ((int) socket != -1) {
  1516. int error;
  1517. closed = true;
  1518. IntPtr x = socket;
  1519. socket = (IntPtr) (-1);
  1520. Close_internal (x, out error);
  1521. if (blocking_thread != null) {
  1522. blocking_thread.Abort ();
  1523. blocking_thread = null;
  1524. }
  1525. if (error != 0)
  1526. throw new SocketException (error);
  1527. }
  1528. }
  1529. void IDisposable.Dispose ()
  1530. {
  1531. Dispose (true);
  1532. GC.SuppressFinalize (this);
  1533. }
  1534. ~Socket () {
  1535. Dispose(false);
  1536. }
  1537. }
  1538. }