Ejemplo n.º 1
0
        protected void InitBase(NetAppConfiguration config, NetLog log)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            IsLittleEndian = BitConverter.IsLittleEndian;
            //if (BitConverter.IsLittleEndian)
            BitWriter = new LittleEndianBitWriter();
            //else
            //	BitWriter = new BigEndianBitWriter();

            Configuration = config;
            Log           = log;

            Configuration.m_isLocked = true;             // prevent changes

            // validate config
            if (config.ApplicationIdentifier == NetConstants.DefaultApplicationIdentifier)
            {
                log.Error("Warning! ApplicationIdentifier not set in configuration!");
            }

            if (this is NetServer)
            {
                if (config.MaximumConnections == -1)
                {
                    throw new ArgumentException("MaximumConnections must be set in configuration!");
                }
                if (config.ServerName == NetConstants.DefaultServerName)
                {
                    log.Warning("Warning! Server name not set!");
                }
            }

            // create buffers
            m_sendBuffer    = new NetBuffer(config.SendBufferSize);
            m_receiveBuffer = new NetBuffer(config.ReceiveBufferSize);

            // Bind to port
            try
            {
                IPEndPoint iep = new IPEndPoint(IPAddress.Any, config.Port);
                EndPoint   ep  = (EndPoint)iep;

                m_socket          = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                m_socket.Blocking = false;
                m_socket.Bind(ep);
                if (iep.Port != 0)
                {
                    Log.Info("Bound to port " + iep.Port);
                }
            }
            catch (SocketException sex)
            {
                if (sex.SocketErrorCode != SocketError.AddressAlreadyInUse)
                {
                    throw new NetException("Failed to bind to port " + config.Port + " - Address already in use!", sex);
                }
            }
            catch (Exception ex)
            {
                throw new NetException("Failed to bind to port " + config.Port, ex);
            }

            m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, config.ReceiveBufferSize);
            m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, config.SendBufferSize);

            m_senderRemote = (EndPoint) new IPEndPoint(IPAddress.Any, 0);
#if DEBUG
            m_lagLoss = new NetLogLossInducer(log);
#endif

            return;
        }
Ejemplo n.º 2
0
        internal int ExecuteSend(NetBuffer buffer, NetConnection connection, IPEndPoint remoteEP)
        {
            if (buffer.LengthBytes < 0)
            {
                Log.Warning("ExecuteSend passed 0 bytes to send");
                return(0);
            }

#if DEBUG
            if (connection != null)
            {
                if (connection.Configuration.SimulateLagLoss && m_lagLoss != null)
                {
                    return(m_lagLoss.ExecuteSend(this, buffer, connection, remoteEP));
                }
            }
#endif
            // encrypt
            if (connection != null && connection.m_encryption.SymmetricEncryptionKeyBytes != null)
            {
                // Log.Debug("SEND: Encrypting packet using key: " + Convert.ToBase64String(connection.SymmetricEncryptionKey));
                connection.m_encryption.EncryptSymmetric(buffer);
            }

            try
            {
                int bytesSent = m_socket.SendTo(buffer.Data, 0, buffer.LengthBytes, SocketFlags.None, remoteEP);

                Debug.Assert(bytesSent == buffer.LengthBytes, "Ouch, sent partial UDP message?!");

                //Log.Verbose(string.Format(CultureInfo.InvariantCulture, "Sent {0} bytes to {1}", bytesSent, remoteEP));
                return(bytesSent);
            }
            catch (SocketException sex)
            {
                if (sex.SocketErrorCode == SocketError.WouldBlock)
                {
                    // send buffer overflow?
#if DEBUG
                    Log.Error("SocketException.WouldBlock thrown during sending; send buffer overflow? Increase buffer using NetAppConfiguration.SendBufferSize");
                    throw new NetException("SocketException.WouldBlock thrown during sending; send buffer overflow? Increase buffer using NetAppConfiguration.SendBufferSize", sex);
#else
                    // let reliability handle it, but log warning
                    Log.Warning("Network send buffer overflow");
#endif
                }

                if (sex.SocketErrorCode == SocketError.ConnectionReset ||
                    sex.SocketErrorCode == SocketError.ConnectionRefused ||
                    sex.SocketErrorCode == SocketError.ConnectionAborted)
                {
                    Log.Warning("Remote socket forcefully closed: " + sex.SocketErrorCode);
                    if (connection != null)
                    {
                        connection.Disconnect("Socket forcefully closed: " + sex.SocketErrorCode);
                    }
                    return(0);
                }

                Log.Warning("Execute SocketException: " + sex.SocketErrorCode);
                return(0);
            }
        }
Ejemplo n.º 3
0
		/// <summary>
		/// Get IP address from notation (xxx.xxx.xxx.xxx) or hostname
		/// </summary>
		public static IPAddress Resolve(NetLog log, string ipOrHost)
		{
			if (log == null)
				throw new ArgumentNullException("log");

			if (string.IsNullOrEmpty(ipOrHost))
				throw new ArgumentException("Supplied string must not be empty", "ipOrHost");

			ipOrHost = ipOrHost.Trim();

			if (m_regIP == null)
			{
				string expression = "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b";
				RegexOptions options = RegexOptions.Compiled;
				m_regIP = new Regex(expression, options);
			}

			// is it an ip number string?
			IPAddress ipAddress = null;
			if (m_regIP.Match(ipOrHost).Success && IPAddress.TryParse(ipOrHost, out ipAddress))
				return ipAddress;

			// ok must be a host name
			IPHostEntry entry;
			try
			{
				entry = Dns.GetHostEntry(ipOrHost);
				if (entry == null)
					return null;

				// check each entry for a valid IP address
				foreach (IPAddress ipCurrent in entry.AddressList)
				{
					string sIP = ipCurrent.ToString();
					bool isIP = m_regIP.Match(sIP).Success && IPAddress.TryParse(sIP, out ipAddress);
					if (isIP)
						break;
				}
				if (ipAddress == null)
					return null;

				return ipAddress;
			}
			catch (SocketException ex)
			{
				if (ex.SocketErrorCode == SocketError.HostNotFound)
				{
					log.Error(string.Format(CultureInfo.InvariantCulture, "Failed to resolve host '{0}'.", ipOrHost));
					return null;
				}
				else
				{
					throw;
				}
			}
		}
Ejemplo n.º 4
0
        /// <summary>
        /// Get IP address from notation (xxx.xxx.xxx.xxx) or hostname
        /// </summary>
        public static IPAddress Resolve(NetLog log, string ipOrHost)
        {
            if (log == null)
            {
                throw new ArgumentNullException("log");
            }

            if (string.IsNullOrEmpty(ipOrHost))
            {
                throw new ArgumentException("Supplied string must not be empty", "ipOrHost");
            }

            ipOrHost = ipOrHost.Trim();

            if (m_regIP == null)
            {
                string       expression = "\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b";
                RegexOptions options    = RegexOptions.Compiled;
                m_regIP = new Regex(expression, options);
            }

            // is it an ip number string?
            IPAddress ipAddress = null;

            if (m_regIP.Match(ipOrHost).Success&& IPAddress.TryParse(ipOrHost, out ipAddress))
            {
                return(ipAddress);
            }

            // ok must be a host name
            IPHostEntry entry;

            try
            {
                entry = Dns.GetHostEntry(ipOrHost);
                if (entry == null)
                {
                    return(null);
                }

                // check each entry for a valid IP address
                foreach (IPAddress ipCurrent in entry.AddressList)
                {
                    string sIP  = ipCurrent.ToString();
                    bool   isIP = m_regIP.Match(sIP).Success&& IPAddress.TryParse(sIP, out ipAddress);
                    if (isIP)
                    {
                        break;
                    }
                }
                if (ipAddress == null)
                {
                    return(null);
                }

                return(ipAddress);
            }
            catch (SocketException ex)
            {
                if (ex.SocketErrorCode == SocketError.HostNotFound)
                {
                    log.Error(string.Format(CultureInfo.InvariantCulture, "Failed to resolve host '{0}'.", ipOrHost));
                    return(null);
                }
                else
                {
                    throw;
                }
            }
        }
Ejemplo n.º 5
0
        protected void InitBase(NetAppConfiguration config, NetLog log)
        {
            if (config == null)
                throw new ArgumentNullException("config");

            if (log == null)
                throw new ArgumentNullException("log");

            IsLittleEndian = BitConverter.IsLittleEndian;
            //if (BitConverter.IsLittleEndian)
            BitWriter = new LittleEndianBitWriter();
            //else
            //	BitWriter = new BigEndianBitWriter();

            Configuration = config;
            Log = log;

            Configuration.m_isLocked = true; // prevent changes

            // validate config
            if (config.ApplicationIdentifier == NetConstants.DefaultApplicationIdentifier)
                log.Error("Warning! ApplicationIdentifier not set in configuration!");

            if (this is NetServer)
            {
                if (config.MaximumConnections == -1)
                    throw new ArgumentException("MaximumConnections must be set in configuration!");
                if (config.ServerName == NetConstants.DefaultServerName)
                    log.Warning("Warning! Server name not set!");
            }

            // create buffers
            m_sendBuffer = new NetBuffer(config.SendBufferSize);
            m_receiveBuffer = new NetBuffer(config.ReceiveBufferSize);

            // Bind to port
            try
            {
                IPEndPoint iep = new IPEndPoint(IPAddress.Any, config.Port);
                EndPoint ep = (EndPoint)iep;

                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                m_socket.Blocking = false;
                m_socket.Bind(ep);
                if (iep.Port != 0)
                    Log.Info("Bound to port " + iep.Port);
            }
            catch (SocketException sex)
            {
                if (sex.SocketErrorCode != SocketError.AddressAlreadyInUse)
                    throw new NetException("Failed to bind to port " + config.Port + " - Address already in use!", sex);
            }
            catch (Exception ex)
            {
                throw new NetException("Failed to bind to port " + config.Port, ex);
            }

            m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, config.ReceiveBufferSize);
            m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, config.SendBufferSize);

            m_senderRemote = (EndPoint)new IPEndPoint(IPAddress.Any, 0);
            #if DEBUG
            m_lagLoss = new NetLogLossInducer(log);
            #endif

            return;
        }