PageRenderTime 28ms CodeModel.GetById 19ms app.highlight 6ms RepoModel.GetById 0ms app.codeStats 1ms

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