/src/Manos.IO/Manos.IO.Libev/IPSocket.cs

http://github.com/jacksonh/manos · C# · 102 lines · 88 code · 14 blank · 0 comment · 15 complexity · 8ef3eca195d19a34c2915c644c661972 MD5 · raw file

  1. using System;
  2. using System.Net;
  3. namespace Manos.IO.Libev
  4. {
  5. abstract class IPSocket<TFragment, TStream> : Socket<TFragment, TStream, IPEndPoint>
  6. where TFragment : class
  7. where TStream : IStream<TFragment>
  8. {
  9. protected IPEndPoint localname, peername;
  10. protected int fd;
  11. protected IPSocket (Context context, AddressFamily addressFamily, ProtocolFamily protocolFamily)
  12. : base (context, addressFamily)
  13. {
  14. int err;
  15. fd = SocketFunctions.manos_socket_create ((int) addressFamily, (int) protocolFamily, out err);
  16. if (fd < 0) {
  17. throw Errors.SocketFailure ("Could not create socket", err);
  18. }
  19. }
  20. protected IPSocket (Context context, AddressFamily addressFamily, int fd)
  21. : base (context, addressFamily)
  22. {
  23. this.fd = fd;
  24. }
  25. public override IPEndPoint LocalEndpoint {
  26. get {
  27. CheckDisposed ();
  28. if (localname == null) {
  29. int err;
  30. ManosIPEndpoint ep;
  31. var result = SocketFunctions.manos_socket_localname_ip (fd, out ep, out err);
  32. if (result < 0) {
  33. throw Errors.SocketFailure ("Could not get local address", err);
  34. }
  35. localname = ep;
  36. }
  37. return localname;
  38. }
  39. }
  40. public override IPEndPoint RemoteEndpoint {
  41. get {
  42. CheckDisposed ();
  43. if (peername == null) {
  44. int err;
  45. ManosIPEndpoint ep;
  46. var result = SocketFunctions.manos_socket_peername_ip (fd, out ep, out err);
  47. if (result < 0) {
  48. throw Errors.SocketFailure ("Could not get remote address", err);
  49. }
  50. peername = ep;
  51. }
  52. return peername;
  53. }
  54. }
  55. public new Context Context {
  56. get { return (Context) base.Context; }
  57. }
  58. public override void Bind (IPEndPoint endpoint)
  59. {
  60. CheckDisposed ();
  61. if (endpoint == null)
  62. throw new ArgumentNullException ("endpoint");
  63. int err;
  64. ManosIPEndpoint ep = endpoint;
  65. var result = SocketFunctions.manos_socket_bind_ip (fd, ref ep, out err);
  66. if (result < 0) {
  67. throw Errors.SocketFailure ("Could not bind to address", err);
  68. } else {
  69. localname = endpoint;
  70. }
  71. IsBound = true;
  72. }
  73. protected void CheckDisposed ()
  74. {
  75. if (fd == 0)
  76. throw new ObjectDisposedException (GetType ().ToString ());
  77. }
  78. protected override void Dispose (bool disposing)
  79. {
  80. if (fd != 0) {
  81. int err;
  82. SocketFunctions.manos_socket_close (fd, out err);
  83. fd = 0;
  84. }
  85. base.Dispose (disposing);
  86. }
  87. }
  88. }