Socket.cs 46 KB

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