Socket.cs 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931
  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. [MonoTODO]
  594. public int SendTimeout {
  595. get {
  596. throw new NotImplementedException ();
  597. }
  598. set {
  599. throw new NotImplementedException ();
  600. }
  601. }
  602. [MonoTODO]
  603. public int ReceiveTimeout {
  604. get {
  605. throw new NotImplementedException ();
  606. }
  607. set {
  608. throw new NotImplementedException ();
  609. }
  610. }
  611. #endif
  612. internal static void CheckProtocolSupport()
  613. {
  614. if(ipv4Supported == -1) {
  615. try {
  616. Socket tmp = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  617. tmp.Close();
  618. ipv4Supported = 1;
  619. }
  620. catch {
  621. ipv4Supported = 0;
  622. }
  623. }
  624. if(ipv6Supported == -1) {
  625. #if NET_2_0 && CONFIGURATION_DEP
  626. SettingsSection config;
  627. config = (SettingsSection) System.Configuration.ConfigurationManager.GetSection ("system.net/settings");
  628. if (config != null)
  629. ipv6Supported = config.Ipv6.Enabled ? -1 : 0;
  630. #else
  631. NetConfig config = (NetConfig)System.Configuration.ConfigurationSettings.GetConfig("system.net/settings");
  632. if(config != null)
  633. ipv6Supported = config.ipv6Enabled?-1:0;
  634. #endif
  635. if(ipv6Supported != 0) {
  636. try {
  637. Socket tmp = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
  638. tmp.Close();
  639. ipv6Supported = 1;
  640. }
  641. catch { }
  642. }
  643. }
  644. }
  645. // Creates a new system socket, returning the handle
  646. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  647. private extern static IntPtr Accept_internal(IntPtr sock,
  648. out int error);
  649. Thread blocking_thread;
  650. public Socket Accept() {
  651. if (disposed && closed)
  652. throw new ObjectDisposedException (GetType ().ToString ());
  653. int error = 0;
  654. IntPtr sock = (IntPtr) (-1);
  655. blocking_thread = Thread.CurrentThread;
  656. try {
  657. sock = Accept_internal(socket, out error);
  658. } catch (ThreadAbortException the) {
  659. if (disposed) {
  660. Thread.ResetAbort ();
  661. error = 10004;
  662. }
  663. } finally {
  664. blocking_thread = null;
  665. }
  666. if (error != 0) {
  667. throw new SocketException (error);
  668. }
  669. Socket accepted = new Socket(this.AddressFamily,
  670. this.SocketType,
  671. this.ProtocolType, sock);
  672. accepted.Blocking = this.Blocking;
  673. return(accepted);
  674. }
  675. public IAsyncResult BeginAccept(AsyncCallback callback,
  676. object state) {
  677. if (disposed && closed)
  678. throw new ObjectDisposedException (GetType ().ToString ());
  679. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Accept);
  680. Worker worker = new Worker (req);
  681. SocketAsyncCall sac = new SocketAsyncCall (worker.Accept);
  682. sac.BeginInvoke (null, req);
  683. return(req);
  684. }
  685. public IAsyncResult BeginConnect(EndPoint end_point,
  686. AsyncCallback callback,
  687. object state) {
  688. if (disposed && closed)
  689. throw new ObjectDisposedException (GetType ().ToString ());
  690. if (end_point == null)
  691. throw new ArgumentNullException ("end_point");
  692. SocketAsyncResult req = new SocketAsyncResult (this, state, callback, SocketOperation.Connect);
  693. req.EndPoint = end_point;
  694. // Bug #75154: Connect() should not succeed for .Any addresses.
  695. if (end_point is IPEndPoint) {
  696. IPEndPoint ep = (IPEndPoint) end_point;
  697. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any)) {
  698. req.Complete (new SocketException (10049), true);
  699. return req;
  700. }
  701. }
  702. int error = 0;
  703. if (!blocking) {
  704. SocketAddress serial = end_point.Serialize ();
  705. Connect_internal (socket, serial, out error);
  706. if (error == 0) {
  707. // succeeded synch
  708. connected = true;
  709. req.Complete (true);
  710. } else if (error != 10036 && error != 10035) {
  711. // error synch
  712. connected = false;
  713. req.Complete (new SocketException (error), true);
  714. }
  715. }
  716. if (blocking || error == 10036 || error == 10035) {
  717. // continue asynch
  718. connected = false;
  719. Worker worker = new Worker (req);
  720. SocketAsyncCall sac = new SocketAsyncCall (worker.Connect);
  721. sac.BeginInvoke (null, req);
  722. }
  723. return(req);
  724. }
  725. public IAsyncResult BeginReceive(byte[] buffer, int offset,
  726. int size,
  727. SocketFlags socket_flags,
  728. AsyncCallback callback,
  729. object state) {
  730. if (disposed && closed)
  731. throw new ObjectDisposedException (GetType ().ToString ());
  732. if (buffer == null)
  733. throw new ArgumentNullException ("buffer");
  734. if (offset < 0 || offset > buffer.Length)
  735. throw new ArgumentOutOfRangeException ("offset");
  736. if (size < 0 || offset + size > buffer.Length)
  737. throw new ArgumentOutOfRangeException ("size");
  738. SocketAsyncResult req;
  739. lock (readQ) {
  740. req = new SocketAsyncResult (this, state, callback, SocketOperation.Receive);
  741. req.Buffer = buffer;
  742. req.Offset = offset;
  743. req.Size = size;
  744. req.SockFlags = socket_flags;
  745. readQ.Enqueue (req);
  746. if (readQ.Count == 1) {
  747. Worker worker = new Worker (req);
  748. SocketAsyncCall sac = new SocketAsyncCall (worker.Receive);
  749. sac.BeginInvoke (null, req);
  750. }
  751. }
  752. return req;
  753. }
  754. public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset,
  755. int size,
  756. SocketFlags socket_flags,
  757. ref EndPoint remote_end,
  758. AsyncCallback callback,
  759. object state) {
  760. if (disposed && closed)
  761. throw new ObjectDisposedException (GetType ().ToString ());
  762. if (buffer == null)
  763. throw new ArgumentNullException ("buffer");
  764. if (offset < 0)
  765. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  766. if (size < 0)
  767. throw new ArgumentOutOfRangeException ("size must be >= 0");
  768. if (offset + size > buffer.Length)
  769. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  770. SocketAsyncResult req;
  771. lock (readQ) {
  772. req = new SocketAsyncResult (this, state, callback, SocketOperation.ReceiveFrom);
  773. req.Buffer = buffer;
  774. req.Offset = offset;
  775. req.Size = size;
  776. req.SockFlags = socket_flags;
  777. req.EndPoint = remote_end;
  778. readQ.Enqueue (req);
  779. if (readQ.Count == 1) {
  780. Worker worker = new Worker (req);
  781. SocketAsyncCall sac = new SocketAsyncCall (worker.ReceiveFrom);
  782. sac.BeginInvoke (null, req);
  783. }
  784. }
  785. return req;
  786. }
  787. public IAsyncResult BeginSend (byte[] buffer, int offset, int size, SocketFlags socket_flags,
  788. AsyncCallback callback, object state)
  789. {
  790. if (disposed && closed)
  791. throw new ObjectDisposedException (GetType ().ToString ());
  792. if (buffer == null)
  793. throw new ArgumentNullException ("buffer");
  794. if (offset < 0)
  795. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  796. if (size < 0)
  797. throw new ArgumentOutOfRangeException ("size must be >= 0");
  798. if (offset + size > buffer.Length)
  799. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  800. SocketAsyncResult req;
  801. lock (writeQ) {
  802. req = new SocketAsyncResult (this, state, callback, SocketOperation.Send);
  803. req.Buffer = buffer;
  804. req.Offset = offset;
  805. req.Size = size;
  806. req.SockFlags = socket_flags;
  807. writeQ.Enqueue (req);
  808. if (writeQ.Count == 1) {
  809. Worker worker = new Worker (req);
  810. SocketAsyncCall sac = new SocketAsyncCall (worker.Send);
  811. sac.BeginInvoke (null, req);
  812. }
  813. }
  814. return req;
  815. }
  816. public IAsyncResult BeginSendTo(byte[] buffer, int offset,
  817. int size,
  818. SocketFlags socket_flags,
  819. EndPoint remote_end,
  820. AsyncCallback callback,
  821. object state) {
  822. if (disposed && closed)
  823. throw new ObjectDisposedException (GetType ().ToString ());
  824. if (buffer == null)
  825. throw new ArgumentNullException ("buffer");
  826. if (offset < 0)
  827. throw new ArgumentOutOfRangeException ("offset must be >= 0");
  828. if (size < 0)
  829. throw new ArgumentOutOfRangeException ("size must be >= 0");
  830. if (offset + size > buffer.Length)
  831. throw new ArgumentOutOfRangeException ("offset + size exceeds the buffer length");
  832. SocketAsyncResult req;
  833. lock (writeQ) {
  834. req = new SocketAsyncResult (this, state, callback, SocketOperation.SendTo);
  835. req.Buffer = buffer;
  836. req.Offset = offset;
  837. req.Size = size;
  838. req.SockFlags = socket_flags;
  839. req.EndPoint = remote_end;
  840. writeQ.Enqueue (req);
  841. if (writeQ.Count == 1) {
  842. Worker worker = new Worker (req);
  843. SocketAsyncCall sac = new SocketAsyncCall (worker.SendTo);
  844. sac.BeginInvoke (null, req);
  845. }
  846. }
  847. return req;
  848. }
  849. // Creates a new system socket, returning the handle
  850. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  851. private extern static void Bind_internal(IntPtr sock,
  852. SocketAddress sa,
  853. out int error);
  854. public void Bind(EndPoint local_end) {
  855. if (disposed && closed)
  856. throw new ObjectDisposedException (GetType ().ToString ());
  857. if(local_end==null) {
  858. throw new ArgumentNullException("local_end");
  859. }
  860. int error;
  861. Bind_internal(socket, local_end.Serialize(),
  862. out error);
  863. if (error != 0) {
  864. throw new SocketException (error);
  865. }
  866. }
  867. // Closes the socket
  868. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  869. private extern static void Close_internal(IntPtr socket,
  870. out int error);
  871. public void Close() {
  872. ((IDisposable) this).Dispose ();
  873. }
  874. // Connects to the remote address
  875. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  876. private extern static void Connect_internal(IntPtr sock,
  877. SocketAddress sa,
  878. out int error);
  879. public void Connect(EndPoint remote_end) {
  880. if (disposed && closed)
  881. throw new ObjectDisposedException (GetType ().ToString ());
  882. if(remote_end==null) {
  883. throw new ArgumentNullException("remote_end");
  884. }
  885. if (remote_end is IPEndPoint) {
  886. IPEndPoint ep = (IPEndPoint) remote_end;
  887. if (ep.Address.Equals (IPAddress.Any) || ep.Address.Equals (IPAddress.IPv6Any))
  888. throw new SocketException (10049);
  889. }
  890. SocketAddress serial = remote_end.Serialize ();
  891. int error = 0;
  892. blocking_thread = Thread.CurrentThread;
  893. try {
  894. Connect_internal (socket, serial, out error);
  895. } catch (ThreadAbortException the) {
  896. if (disposed) {
  897. Thread.ResetAbort ();
  898. error = 10004;
  899. }
  900. } finally {
  901. blocking_thread = null;
  902. }
  903. if (error != 0) {
  904. throw new SocketException (error);
  905. }
  906. connected=true;
  907. }
  908. public Socket EndAccept(IAsyncResult result) {
  909. if (disposed && closed)
  910. throw new ObjectDisposedException (GetType ().ToString ());
  911. if (result == null)
  912. throw new ArgumentNullException ("result");
  913. SocketAsyncResult req = result as SocketAsyncResult;
  914. if (req == null)
  915. throw new ArgumentException ("Invalid IAsyncResult", "result");
  916. if (!result.IsCompleted)
  917. result.AsyncWaitHandle.WaitOne();
  918. req.CheckIfThrowDelayedException();
  919. return req.Socket;
  920. }
  921. public void EndConnect(IAsyncResult result) {
  922. if (disposed && closed)
  923. throw new ObjectDisposedException (GetType ().ToString ());
  924. if (result == null)
  925. throw new ArgumentNullException ("result");
  926. SocketAsyncResult req = result as SocketAsyncResult;
  927. if (req == null)
  928. throw new ArgumentException ("Invalid IAsyncResult", "result");
  929. if (!result.IsCompleted)
  930. result.AsyncWaitHandle.WaitOne();
  931. req.CheckIfThrowDelayedException();
  932. }
  933. public int EndReceive(IAsyncResult result) {
  934. if (disposed && closed)
  935. throw new ObjectDisposedException (GetType ().ToString ());
  936. if (result == null)
  937. throw new ArgumentNullException ("result");
  938. SocketAsyncResult req = result as SocketAsyncResult;
  939. if (req == null)
  940. throw new ArgumentException ("Invalid IAsyncResult", "result");
  941. if (!result.IsCompleted)
  942. result.AsyncWaitHandle.WaitOne();
  943. req.CheckIfThrowDelayedException();
  944. return req.Total;
  945. }
  946. public int EndReceiveFrom(IAsyncResult result,
  947. ref EndPoint end_point) {
  948. if (disposed && closed)
  949. throw new ObjectDisposedException (GetType ().ToString ());
  950. if (result == null)
  951. throw new ArgumentNullException ("result");
  952. SocketAsyncResult req = result as SocketAsyncResult;
  953. if (req == null)
  954. throw new ArgumentException ("Invalid IAsyncResult", "result");
  955. if (!result.IsCompleted)
  956. result.AsyncWaitHandle.WaitOne();
  957. req.CheckIfThrowDelayedException();
  958. end_point = req.EndPoint;
  959. return req.Total;
  960. }
  961. public int EndSend(IAsyncResult result) {
  962. if (disposed && closed)
  963. throw new ObjectDisposedException (GetType ().ToString ());
  964. if (result == null)
  965. throw new ArgumentNullException ("result");
  966. SocketAsyncResult req = result as SocketAsyncResult;
  967. if (req == null)
  968. throw new ArgumentException ("Invalid IAsyncResult", "result");
  969. if (!result.IsCompleted)
  970. result.AsyncWaitHandle.WaitOne();
  971. req.CheckIfThrowDelayedException();
  972. return req.Total;
  973. }
  974. public int EndSendTo(IAsyncResult result) {
  975. if (disposed && closed)
  976. throw new ObjectDisposedException (GetType ().ToString ());
  977. if (result == null)
  978. throw new ArgumentNullException ("result");
  979. SocketAsyncResult req = result as SocketAsyncResult;
  980. if (req == null)
  981. throw new ArgumentException ("Invalid IAsyncResult", "result");
  982. if (!result.IsCompleted)
  983. result.AsyncWaitHandle.WaitOne();
  984. req.CheckIfThrowDelayedException();
  985. return req.Total;
  986. }
  987. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  988. private extern static void GetSocketOption_obj_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, out object obj_val, out int error);
  989. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  990. private extern static void GetSocketOption_arr_internal(IntPtr socket, SocketOptionLevel level, SocketOptionName name, ref byte[] byte_val, out int error);
  991. public object GetSocketOption (SocketOptionLevel level, SocketOptionName name)
  992. {
  993. if (disposed && closed)
  994. throw new ObjectDisposedException (GetType ().ToString ());
  995. object obj_val;
  996. int error;
  997. GetSocketOption_obj_internal(socket, level, name,
  998. out obj_val, out error);
  999. if (error != 0) {
  1000. throw new SocketException (error);
  1001. }
  1002. if(name==SocketOptionName.Linger) {
  1003. return((LingerOption)obj_val);
  1004. } else if (name==SocketOptionName.AddMembership ||
  1005. name==SocketOptionName.DropMembership) {
  1006. return((MulticastOption)obj_val);
  1007. } else if (obj_val is int) {
  1008. return((int)obj_val);
  1009. } else {
  1010. return(obj_val);
  1011. }
  1012. }
  1013. public void GetSocketOption (SocketOptionLevel level, SocketOptionName name, byte [] opt_value)
  1014. {
  1015. if (disposed && closed)
  1016. throw new ObjectDisposedException (GetType ().ToString ());
  1017. int error;
  1018. GetSocketOption_arr_internal(socket, level, name,
  1019. ref opt_value, out error);
  1020. if (error != 0) {
  1021. throw new SocketException (error);
  1022. }
  1023. }
  1024. public byte [] GetSocketOption (SocketOptionLevel level, SocketOptionName name, int length)
  1025. {
  1026. if (disposed && closed)
  1027. throw new ObjectDisposedException (GetType ().ToString ());
  1028. byte[] byte_val=new byte[length];
  1029. int error;
  1030. GetSocketOption_arr_internal(socket, level, name,
  1031. ref byte_val, out error);
  1032. if (error != 0) {
  1033. throw new SocketException (error);
  1034. }
  1035. return(byte_val);
  1036. }
  1037. // See Socket.IOControl, WSAIoctl documentation in MSDN. The
  1038. // common options between UNIX and Winsock are FIONREAD,
  1039. // FIONBIO and SIOCATMARK. Anything else will depend on the
  1040. // system.
  1041. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1042. extern static int WSAIoctl (IntPtr sock, int ioctl_code,
  1043. byte [] input, byte [] output,
  1044. out int error);
  1045. public int IOControl (int ioctl_code, byte [] in_value, byte [] out_value)
  1046. {
  1047. if (disposed)
  1048. throw new ObjectDisposedException (GetType ().ToString ());
  1049. int error;
  1050. int result = WSAIoctl (socket, ioctl_code, in_value,
  1051. out_value, out error);
  1052. if (error != 0) {
  1053. throw new SocketException (error);
  1054. }
  1055. if (result == -1)
  1056. throw new InvalidOperationException ("Must use Blocking property instead.");
  1057. return result;
  1058. }
  1059. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1060. private extern static void Listen_internal(IntPtr sock,
  1061. int backlog,
  1062. out int error);
  1063. public void Listen (int backlog)
  1064. {
  1065. if (disposed && closed)
  1066. throw new ObjectDisposedException (GetType ().ToString ());
  1067. int error;
  1068. Listen_internal(socket, backlog, out error);
  1069. if (error != 0) {
  1070. throw new SocketException (error);
  1071. }
  1072. }
  1073. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1074. extern static bool Poll_internal (IntPtr socket, SelectMode mode, int timeout, out int error);
  1075. public bool Poll (int time_us, SelectMode mode)
  1076. {
  1077. if (disposed && closed)
  1078. throw new ObjectDisposedException (GetType ().ToString ());
  1079. if (mode != SelectMode.SelectRead &&
  1080. mode != SelectMode.SelectWrite &&
  1081. mode != SelectMode.SelectError)
  1082. throw new NotSupportedException ("'mode' parameter is not valid.");
  1083. int error;
  1084. bool result = Poll_internal (socket, mode, time_us, out error);
  1085. if (error != 0)
  1086. throw new SocketException (error);
  1087. if (result == true) {
  1088. /* Update the connected state; for
  1089. * non-blocking Connect()s this is
  1090. * when we can find out that the
  1091. * connect succeeded.
  1092. */
  1093. connected = true;
  1094. }
  1095. return result;
  1096. }
  1097. public int Receive (byte [] buf)
  1098. {
  1099. if (disposed && closed)
  1100. throw new ObjectDisposedException (GetType ().ToString ());
  1101. if (buf == null)
  1102. throw new ArgumentNullException ("buf");
  1103. SocketError error;
  1104. int ret = Receive_nochecks (buf, 0, buf.Length, SocketFlags.None, out error);
  1105. if (error != SocketError.Success)
  1106. throw new SocketException ((int) error);
  1107. return ret;
  1108. }
  1109. public int Receive (byte [] buf, SocketFlags flags)
  1110. {
  1111. if (disposed && closed)
  1112. throw new ObjectDisposedException (GetType ().ToString ());
  1113. if (buf == null)
  1114. throw new ArgumentNullException ("buf");
  1115. SocketError error;
  1116. int ret = Receive_nochecks (buf, 0, buf.Length, flags, out error);
  1117. if (error != SocketError.Success)
  1118. throw new SocketException ((int) error);
  1119. return ret;
  1120. }
  1121. public int Receive (byte [] buf, int size, SocketFlags flags)
  1122. {
  1123. if (disposed && closed)
  1124. throw new ObjectDisposedException (GetType ().ToString ());
  1125. if (buf == null)
  1126. throw new ArgumentNullException ("buf");
  1127. if (size < 0 || size > buf.Length)
  1128. throw new ArgumentOutOfRangeException ("size");
  1129. SocketError error;
  1130. int ret = Receive_nochecks (buf, 0, size, flags, out error);
  1131. if (error != SocketError.Success)
  1132. throw new SocketException ((int) error);
  1133. return ret;
  1134. }
  1135. public int Receive (byte [] buf, int offset, int size, SocketFlags flags)
  1136. {
  1137. if (disposed && closed)
  1138. throw new ObjectDisposedException (GetType ().ToString ());
  1139. if (buf == null)
  1140. throw new ArgumentNullException ("buf");
  1141. if (offset < 0 || offset > buf.Length)
  1142. throw new ArgumentOutOfRangeException ("offset");
  1143. if (size < 0 || offset + size > buf.Length)
  1144. throw new ArgumentOutOfRangeException ("size");
  1145. SocketError error;
  1146. int ret = Receive_nochecks (buf, offset, size, flags, out error);
  1147. if(error != SocketError.Success)
  1148. throw new SocketException ((int) error);
  1149. return ret;
  1150. }
  1151. #if NET_2_0
  1152. public int Receive (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  1153. {
  1154. if (disposed && closed)
  1155. throw new ObjectDisposedException (GetType ().ToString ());
  1156. if (buf == null)
  1157. throw new ArgumentNullException ("buf");
  1158. if (offset < 0 || offset > buf.Length)
  1159. throw new ArgumentOutOfRangeException ("offset");
  1160. if (size < 0 || offset + size > buf.Length)
  1161. throw new ArgumentOutOfRangeException ("size");
  1162. return Receive_nochecks (buf, offset, size, flags, out error);
  1163. }
  1164. #endif
  1165. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1166. private extern static int Receive_internal(IntPtr sock,
  1167. byte[] buffer,
  1168. int offset,
  1169. int count,
  1170. SocketFlags flags,
  1171. out int error);
  1172. int Receive_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  1173. {
  1174. int nativeError;
  1175. int ret = Receive_internal (socket, buf, offset, size, flags, out nativeError);
  1176. error = (SocketError) nativeError;
  1177. if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress)
  1178. connected = false;
  1179. else
  1180. connected = true;
  1181. return ret;
  1182. }
  1183. public int ReceiveFrom (byte [] buf, ref EndPoint remote_end)
  1184. {
  1185. if (disposed && closed)
  1186. throw new ObjectDisposedException (GetType ().ToString ());
  1187. if (buf == null)
  1188. throw new ArgumentNullException ("buf");
  1189. if (remote_end == null)
  1190. throw new ArgumentNullException ("remote_end");
  1191. return ReceiveFrom_nochecks (buf, 0, buf.Length, SocketFlags.None, ref remote_end);
  1192. }
  1193. public int ReceiveFrom (byte [] buf, SocketFlags flags, ref EndPoint remote_end)
  1194. {
  1195. if (disposed && closed)
  1196. throw new ObjectDisposedException (GetType ().ToString ());
  1197. if (buf == null)
  1198. throw new ArgumentNullException ("buf");
  1199. if (remote_end == null)
  1200. throw new ArgumentNullException ("remote_end");
  1201. return ReceiveFrom_nochecks (buf, 0, buf.Length, flags, ref remote_end);
  1202. }
  1203. public int ReceiveFrom (byte [] buf, int size, SocketFlags flags,
  1204. ref EndPoint remote_end)
  1205. {
  1206. if (disposed && closed)
  1207. throw new ObjectDisposedException (GetType ().ToString ());
  1208. if (buf == null)
  1209. throw new ArgumentNullException ("buf");
  1210. if (remote_end == null)
  1211. throw new ArgumentNullException ("remote_end");
  1212. if (size < 0 || size > buf.Length)
  1213. throw new ArgumentOutOfRangeException ("size");
  1214. return ReceiveFrom_nochecks (buf, 0, size, flags, ref remote_end);
  1215. }
  1216. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1217. private extern static int RecvFrom_internal(IntPtr sock,
  1218. byte[] buffer,
  1219. int offset,
  1220. int count,
  1221. SocketFlags flags,
  1222. ref SocketAddress sockaddr,
  1223. out int error);
  1224. public int ReceiveFrom (byte [] buf, int offset, int size, SocketFlags flags,
  1225. ref EndPoint remote_end)
  1226. {
  1227. if (disposed && closed)
  1228. throw new ObjectDisposedException (GetType ().ToString ());
  1229. if (buf == null)
  1230. throw new ArgumentNullException ("buf");
  1231. if (remote_end == null)
  1232. throw new ArgumentNullException ("remote_end");
  1233. if (offset < 0 || offset > buf.Length)
  1234. throw new ArgumentOutOfRangeException ("offset");
  1235. if (size < 0 || offset + size > buf.Length)
  1236. throw new ArgumentOutOfRangeException ("size");
  1237. return ReceiveFrom_nochecks (buf, offset, size, flags, ref remote_end);
  1238. }
  1239. int ReceiveFrom_nochecks (byte [] buf, int offset, int size, SocketFlags flags,
  1240. ref EndPoint remote_end)
  1241. {
  1242. SocketAddress sockaddr = remote_end.Serialize();
  1243. int cnt, error;
  1244. cnt = RecvFrom_internal (socket, buf, offset, size, flags, ref sockaddr, out error);
  1245. if (error != 0) {
  1246. if (error != 10035 && error != 10036) // WSAEWOULDBLOCK && WSAEINPROGRESS
  1247. connected = false;
  1248. throw new SocketException (error);
  1249. }
  1250. connected = true;
  1251. // If sockaddr is null then we're a connection
  1252. // oriented protocol and should ignore the
  1253. // remote_end parameter (see MSDN
  1254. // documentation for Socket.ReceiveFrom(...) )
  1255. if ( sockaddr != null ) {
  1256. // Stupidly, EndPoint.Create() is an
  1257. // instance method
  1258. remote_end = remote_end.Create (sockaddr);
  1259. }
  1260. return cnt;
  1261. }
  1262. public int Send (byte [] buf)
  1263. {
  1264. if (disposed && closed)
  1265. throw new ObjectDisposedException (GetType ().ToString ());
  1266. if (buf == null)
  1267. throw new ArgumentNullException ("buf");
  1268. SocketError error;
  1269. int ret = Send_nochecks (buf, 0, buf.Length, SocketFlags.None, out error);
  1270. if (error != SocketError.Success)
  1271. throw new SocketException ((int) error);
  1272. return ret;
  1273. }
  1274. public int Send (byte [] buf, SocketFlags flags)
  1275. {
  1276. if (disposed && closed)
  1277. throw new ObjectDisposedException (GetType ().ToString ());
  1278. if (buf == null)
  1279. throw new ArgumentNullException ("buf");
  1280. SocketError error;
  1281. int ret = Send_nochecks (buf, 0, buf.Length, flags, out error);
  1282. if (error != SocketError.Success)
  1283. throw new SocketException ((int) error);
  1284. return ret;
  1285. }
  1286. public int Send (byte [] buf, int size, SocketFlags flags)
  1287. {
  1288. if (disposed && closed)
  1289. throw new ObjectDisposedException (GetType ().ToString ());
  1290. if (buf == null)
  1291. throw new ArgumentNullException ("buf");
  1292. if (size < 0 || size > buf.Length)
  1293. throw new ArgumentOutOfRangeException ("size");
  1294. SocketError error;
  1295. int ret = Send_nochecks (buf, 0, size, flags, out error);
  1296. if (error != SocketError.Success)
  1297. throw new SocketException ((int) error);
  1298. return ret;
  1299. }
  1300. public int Send (byte [] buf, int offset, int size, SocketFlags flags)
  1301. {
  1302. if (disposed && closed)
  1303. throw new ObjectDisposedException (GetType ().ToString ());
  1304. if (buf == null)
  1305. throw new ArgumentNullException ("buffer");
  1306. if (offset < 0 || offset > buf.Length)
  1307. throw new ArgumentOutOfRangeException ("offset");
  1308. if (size < 0 || offset + size > buf.Length)
  1309. throw new ArgumentOutOfRangeException ("size");
  1310. SocketError error;
  1311. int ret = Send_nochecks (buf, offset, size, flags, out error);
  1312. if (error != SocketError.Success)
  1313. throw new SocketException ((int) error);
  1314. return ret;
  1315. }
  1316. #if NET_2_0
  1317. public int Send (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  1318. {
  1319. if (disposed && closed)
  1320. throw new ObjectDisposedException (GetType ().ToString ());
  1321. if (buf == null)
  1322. throw new ArgumentNullException ("buffer");
  1323. if (offset < 0 || offset > buf.Length)
  1324. throw new ArgumentOutOfRangeException ("offset");
  1325. if (size < 0 || offset + size > buf.Length)
  1326. throw new ArgumentOutOfRangeException ("size");
  1327. return Send_nochecks (buf, offset, size, flags, out error);
  1328. }
  1329. #endif
  1330. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1331. private extern static int Send_internal(IntPtr sock,
  1332. byte[] buf, int offset,
  1333. int count,
  1334. SocketFlags flags,
  1335. out int error);
  1336. int Send_nochecks (byte [] buf, int offset, int size, SocketFlags flags, out SocketError error)
  1337. {
  1338. if (size == 0) {
  1339. error = SocketError.Success;
  1340. return 0;
  1341. }
  1342. int nativeError;
  1343. int ret = Send_internal (socket, buf, offset, size, flags, out nativeError);
  1344. error = (SocketError)nativeError;
  1345. if (error != SocketError.Success && error != SocketError.WouldBlock && error != SocketError.InProgress)
  1346. connected = false;
  1347. else
  1348. connected = true;
  1349. return ret;
  1350. }
  1351. public int SendTo (byte [] buffer, EndPoint remote_end)
  1352. {
  1353. if (disposed && closed)
  1354. throw new ObjectDisposedException (GetType ().ToString ());
  1355. if (buffer == null)
  1356. throw new ArgumentNullException ("buffer");
  1357. if (remote_end == null)
  1358. throw new ArgumentNullException ("remote_end");
  1359. return SendTo_nochecks (buffer, 0, buffer.Length, SocketFlags.None, remote_end);
  1360. }
  1361. public int SendTo (byte [] buffer, SocketFlags flags, EndPoint remote_end)
  1362. {
  1363. if (disposed && closed)
  1364. throw new ObjectDisposedException (GetType ().ToString ());
  1365. if (buffer == null)
  1366. throw new ArgumentNullException ("buffer");
  1367. if (remote_end == null)
  1368. throw new ArgumentNullException ("remote_end");
  1369. return SendTo_nochecks (buffer, 0, buffer.Length, flags, remote_end);
  1370. }
  1371. public int SendTo (byte [] buffer, int size, SocketFlags flags, EndPoint remote_end)
  1372. {
  1373. if (disposed && closed)
  1374. throw new ObjectDisposedException (GetType ().ToString ());
  1375. if (buffer == null)
  1376. throw new ArgumentNullException ("buffer");
  1377. if (remote_end == null)
  1378. throw new ArgumentNullException ("remote_end");
  1379. if (size < 0 || size > buffer.Length)
  1380. throw new ArgumentOutOfRangeException ("size");
  1381. return SendTo_nochecks (buffer, 0, size, flags, remote_end);
  1382. }
  1383. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1384. private extern static int SendTo_internal(IntPtr sock,
  1385. byte[] buffer,
  1386. int offset,
  1387. int count,
  1388. SocketFlags flags,
  1389. SocketAddress sa,
  1390. out int error);
  1391. public int SendTo (byte [] buffer, int offset, int size, SocketFlags flags,
  1392. EndPoint remote_end)
  1393. {
  1394. if (disposed && closed)
  1395. throw new ObjectDisposedException (GetType ().ToString ());
  1396. if (buffer == null)
  1397. throw new ArgumentNullException ("buffer");
  1398. if (remote_end == null)
  1399. throw new ArgumentNullException("remote_end");
  1400. if (offset < 0 || offset > buffer.Length)
  1401. throw new ArgumentOutOfRangeException ("offset");
  1402. if (size < 0 || offset + size > buffer.Length)
  1403. throw new ArgumentOutOfRangeException ("size");
  1404. return SendTo_nochecks (buffer, offset, size, flags, remote_end);
  1405. }
  1406. int SendTo_nochecks (byte [] buffer, int offset, int size, SocketFlags flags,
  1407. EndPoint remote_end)
  1408. {
  1409. SocketAddress sockaddr = remote_end.Serialize ();
  1410. int ret, error;
  1411. ret = SendTo_internal (socket, buffer, offset, size, flags, sockaddr, out error);
  1412. if (error != 0) {
  1413. if (error != 10035 && error != 10036) // WSAEWOULDBLOCK && WSAEINPROGRESS
  1414. connected = false;
  1415. throw new SocketException (error);
  1416. }
  1417. connected = true;
  1418. return ret;
  1419. }
  1420. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1421. private extern static void SetSocketOption_internal (IntPtr socket, SocketOptionLevel level,
  1422. SocketOptionName name, object obj_val,
  1423. byte [] byte_val, int int_val,
  1424. out int error);
  1425. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, byte[] opt_value)
  1426. {
  1427. if (disposed && closed)
  1428. throw new ObjectDisposedException (GetType ().ToString ());
  1429. int error;
  1430. SetSocketOption_internal(socket, level, name, null,
  1431. opt_value, 0, out error);
  1432. if (error != 0) {
  1433. throw new SocketException (error);
  1434. }
  1435. }
  1436. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, int opt_value)
  1437. {
  1438. if (disposed && closed)
  1439. throw new ObjectDisposedException (GetType ().ToString ());
  1440. int error;
  1441. SetSocketOption_internal(socket, level, name, null,
  1442. null, opt_value, out error);
  1443. if (error != 0) {
  1444. throw new SocketException (error);
  1445. }
  1446. }
  1447. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, object opt_value)
  1448. {
  1449. if (disposed && closed)
  1450. throw new ObjectDisposedException (GetType ().ToString ());
  1451. if(opt_value==null) {
  1452. throw new ArgumentNullException();
  1453. }
  1454. int error;
  1455. /* From MS documentation on SetSocketOption: "For an
  1456. * option with a Boolean data type, specify a nonzero
  1457. * value to enable the option, and a zero value to
  1458. * disable the option."
  1459. * Booleans are only handled in 2.0
  1460. */
  1461. if (opt_value is System.Boolean) {
  1462. #if NET_2_0
  1463. bool bool_val = (bool) opt_value;
  1464. int int_val = (bool_val) ? 1 : 0;
  1465. SetSocketOption_internal (socket, level, name, null, null, int_val, out error);
  1466. #else
  1467. throw new ArgumentException ("Use an integer 1 (true) or 0 (false) instead of a boolean.", "opt_value");
  1468. #endif
  1469. } else {
  1470. SetSocketOption_internal (socket, level, name, opt_value, null, 0, out error);
  1471. }
  1472. if (error != 0)
  1473. throw new SocketException (error);
  1474. }
  1475. #if NET_2_0
  1476. public void SetSocketOption (SocketOptionLevel level, SocketOptionName name, bool optionValue)
  1477. {
  1478. if (disposed && closed)
  1479. throw new ObjectDisposedException (GetType ().ToString ());
  1480. int error;
  1481. int int_val = (optionValue) ? 1 : 0;
  1482. SetSocketOption_internal (socket, level, name, null, null, int_val, out error);
  1483. if (error != 0)
  1484. throw new SocketException (error);
  1485. }
  1486. #endif
  1487. [MethodImplAttribute(MethodImplOptions.InternalCall)]
  1488. private extern static void Shutdown_internal(IntPtr socket, SocketShutdown how, out int error);
  1489. public void Shutdown (SocketShutdown how)
  1490. {
  1491. if (disposed && closed)
  1492. throw new ObjectDisposedException (GetType ().ToString ());
  1493. int error;
  1494. Shutdown_internal(socket, how, out error);
  1495. if (error != 0) {
  1496. throw new SocketException (error);
  1497. }
  1498. }
  1499. public override int GetHashCode ()
  1500. {
  1501. return (int) socket;
  1502. }
  1503. protected virtual void Dispose (bool explicitDisposing)
  1504. {
  1505. if (disposed)
  1506. return;
  1507. disposed = true;
  1508. connected = false;
  1509. if ((int) socket != -1) {
  1510. int error;
  1511. closed = true;
  1512. IntPtr x = socket;
  1513. socket = (IntPtr) (-1);
  1514. Close_internal (x, out error);
  1515. if (blocking_thread != null) {
  1516. blocking_thread.Abort ();
  1517. blocking_thread = null;
  1518. }
  1519. if (error != 0)
  1520. throw new SocketException (error);
  1521. }
  1522. }
  1523. void IDisposable.Dispose ()
  1524. {
  1525. Dispose (true);
  1526. GC.SuppressFinalize (this);
  1527. }
  1528. ~Socket () {
  1529. Dispose(false);
  1530. }
  1531. }
  1532. }