Equals() public method

public Equals ( object comparand ) : bool
comparand object
return bool
 public static void ValidateListenIPAddress(IPAddress address)
 {
     if ((address != null) && (((address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) || (address.Equals(IPAddress.IPv6None) || address.Equals(IPAddress.None))) || ((address.Equals(IPAddress.Broadcast) || address.IsIPv6Multicast) || IPAddress.IsLoopback(address))))
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(System.ServiceModel.SR.GetString("PeerListenIPAddressInvalid", new object[] { address }), "address", null));
     }
 }
Exemplo n.º 2
0
		public static IPAddress GetMatchingLocalIP(IPAddress clientAddr)
		{
			if (clientAddr.Equals(IPAddress.Any) ||
				clientAddr.Equals(IPAddress.Loopback))
			{
				return IPAddress.Loopback;
			}

			var clientBytes = clientAddr.GetAddressBytes();

			// find an address that matches the most significant n-1 bytes of the address of the connecting client
			foreach (var addr in CachedHostEntry.AddressList)
			{
				var bytes = addr.GetAddressBytes();
				if (bytes.Length != clientBytes.Length) continue;

				var match = true;
				for (var i = bytes.Length-2; i >= 0; i--)
				{
					if (bytes[i] != clientBytes[i])
					{
						match = false;
						break;
					}
				}
				if (match) return addr;
			}
			return null;
		}
Exemplo n.º 3
0
        private void ReceivePacketListener(IAsyncResult result)
        {
            try
            {
                int received = socket.EndReceive(result);
                if (received > 20)
                {
                    // Decode the packet if it is UDP
                    byte protocol = buffer[9];
                    if (protocol == 0x11)
                    {
                        // Source (offset=12)
                        byte[] srcBytes = new byte[4];
                        Array.Copy(buffer, 12, srcBytes, 0, srcBytes.Length);
                        IPAddress sourceIP = new System.Net.IPAddress(srcBytes);

                        // Destination (offset=16)
                        byte[] destBytes = new byte[4];
                        Array.Copy(buffer, 16, destBytes, 0, destBytes.Length);
                        IPAddress destIP = new System.Net.IPAddress(destBytes);

                        // Source port (offset=20)
                        int srcPort = (int)buffer[20] << 8 | (int)buffer[21];

                        // Destination port (offset=22)
                        int destPort = (int)buffer[22] << 8 | (int)buffer[23];

                        // Inbound traffic
                        if (!sourceIP.Equals(adapterIP) && destIP.Equals(adapterIP))
                        {
                            if (destPort >= AppSettings.Default.setNetLowPort &&
                                destPort <= AppSettings.Default.setNetHighPort)
                            {
                                RecordRxData(sourceIP, received);
                            }
                        }
                        // Outbound traffic
                        else if (sourceIP.Equals(adapterIP) && !destIP.Equals(adapterIP))
                        {
                            if (srcPort >= AppSettings.Default.setNetLowPort &&
                                srcPort <= AppSettings.Default.setNetHighPort)
                            {
                                RecordTxData(destIP, received);
                            }
                        }
                    }
                }
            }
            catch { }
            try
            {
                if (isActive)
                {
                    socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(this.ReceivePacketListener), null);
                }
            }
            catch { }
        }
Exemplo n.º 4
0
        // outgoing
        internal UdpTransport(IPAddress address, int port, ulong connectionType)
        {
            if (address.Equals (IPAddress.Any) || address.Equals (IPAddress.None) || port == 0)
                throw new Exception ("Invalid IP Address/Port");

            this.remoteEndPoint = new IPEndPoint (address, port);
            base.connectionType = connectionType;
            base.incoming = false;
            base.transportState = TransportState.Waiting;
        }
Exemplo n.º 5
0
        // End of added code

        private void connectButton_Click(object sender, EventArgs e)
        {
            if (IpAdressTextBox.Text != null && IpAdressTextBox.Text != "")
            {
                ((MainWindow)(this.Owner)).logWindow.Message = ((MainWindow)(this.Owner)).logMessagesHashTable["logMessage_searchingByIpAttemptingToConnect"].ToString();
                this.Cursor = Cursors.WaitCursor;

                Communication.CardID = 255;
                System.Net.IPAddress testedIP = System.Net.IPAddress.Parse("0.0.0.0");
                AvailableSocket      tmp      = NetworkCommunication.TestGivenSocket(IpAdressTextBox.Text);
                if (testedIP.Equals(tmp.Ip))
                {
                    ((MainWindow)(this.Owner)).logWindow.Message = ((MainWindow)(this.Owner)).logMessagesHashTable["logMessage_searchingByIpUnableToConnect"].ToString();
                    //MessageBox.Show("The screen was not found via network connection.\nProbably given IP was misstyped.", "BengiLED - Connection Failure", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    found = false;
                }
                else
                {
                    NetworkCommunication.SocketsList.Add(tmp);
                    ((MainWindow)(this.Owner)).logWindow.Message = string.Format("{0} {1}", ((MainWindow)(this.Owner)).logMessagesHashTable["logMessage_searchingByIpFoundIpIs"].ToString(), NetworkCommunication.SocketsList[0].Ip);
                    //MessageBox.Show(string.Format("The screen was found via network connection. IP is {0}", NetworkCommunication.SocketsList[0].Ip), "BengiLED - Connection Succes", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    found = true;
                    this.Close();
                }

                this.Cursor = Cursors.Default;
            }
        }
Exemplo n.º 6
0
        public bool TestDefaultIP()
        {
            string defaultIP = ((MainWindow)this.Owner).ConfigHashtable["CurrentIP"].ToString();

            Communication.Type = CommunicationType.Network;

            System.Net.IPAddress testedIP = System.Net.IPAddress.Parse("0.0.0.0");
            AvailableSocket      tmp      = NetworkCommunication.TestGivenSocket(defaultIP);

            if (testedIP.Equals(tmp.Ip))
            {
                ((MainWindow)(this.Owner)).logWindow.Message = ((MainWindow)(this.Owner)).logMessagesHashTable["logMessage_searchingByIpDefaultNotFound"].ToString();
                //MessageBox.Show("The screen was not found via network default IP address.", "BengiLED - Connection Failure", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Communication.Type = CommunicationType.None;

                return(false);
            }
            else
            {
                NetworkCommunication.SocketsList.Add(tmp);
                ((MainWindow)(this.Owner)).logWindow.Message = string.Format("{0} {1}", ((MainWindow)(this.Owner)).logMessagesHashTable["logMessage_searchingByIpFoundIpIsDefault"].ToString(), NetworkCommunication.SocketsList[0].Ip);
                //MessageBox.Show(string.Format("The screen was found via network connection. IP is default {0}", NetworkCommunication.SocketsList[0].Ip), "BengiLED - Connection Succes", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return(true);
            }
        }
Exemplo n.º 7
0
 public override string ToString()
 {
     if (IsNull(this.from_) || IsNull(this.to_) || from_.Equals(to_))
     {
         return(From.ToString());
     }
     return(string.Format("{0}-{1}", From, To));
 }
Exemplo n.º 8
0
        public bool IsOnIntranet(IPAddress ipAddress)
        {
            if (empty.Equals(ipAddress))
            {
                return false;
            }
            bool onIntranet = IPAddress.IsLoopback(ipAddress);
            onIntranet = onIntranet ||
              ipAddress.Equals(And(ipAddress,intranetMask1)); //10.255.255.255
            onIntranet = onIntranet ||
              ipAddress.Equals(And(ipAddress,intranetMask4)); ////192.168.255.255

            onIntranet = onIntranet || (intranetMask2.Equals(And(ipAddress,intranetMask2))
              && ipAddress.Equals(And(ipAddress,intranetMask3)));

            return onIntranet;
        }
Exemplo n.º 9
0
		/// <summary>
		///     Sends a ping using IcmpSendEcho2Ex function in Iphlpapi.dll. Use this method when you need to specify a source
		///     interface for a ping otherwise use .NET ping implementation.
		/// </summary>
		/// <param name="srcAddress">The IPv4 source address on which to issue the echo request.</param>
		/// <param name="destAddress">The IPv4 destination of the echo request.</param>
		/// <param name="timeout">The time, in milliseconds, to wait for replies.</param>
		/// <param name="buffer">A buffer that contains data to send in the request.</param>
		/// <param name="po">IP header options for the request.</param>
		/// <exception cref="ArgumentNullException"></exception>
		/// <exception cref="FormatException">When the destination address is no valid IpV4 address or not defining a specific IP.</exception>
		public static PingReply SendPing(IPAddress srcAddress, IPAddress destAddress, int timeout = 5000, byte[] buffer = null, PingOptions po = null)
		{
			if (destAddress == null)
				throw new ArgumentNullException("destAddress");
			if (destAddress.AddressFamily != AddressFamily.InterNetwork || srcAddress.AddressFamily != AddressFamily.InterNetwork || destAddress.Equals(IPAddress.Any))
				throw new FormatException();

			//Defining p invoke arguments.
			var source = srcAddress == null ? 0 : BitConverter.ToUInt32(srcAddress.GetAddressBytes(), 0);
			var destination = BitConverter.ToUInt32(destAddress.GetAddressBytes(), 0);
			var sendbuffer = buffer ?? new byte[] {};
			var options = new Interop.Option
						{
							Ttl = (po == null ? (byte) 255 : (byte) po.Ttl),
							Flags = (po == null ? (byte) 0 : po.DontFragment ? (byte) 0x02 : (byte) 0) //0x02
						};
			var fullReplyBufferSize = Interop.ReplyMarshalLength + sendbuffer.Length; //Size of Reply structure plus the transmitted buffer length.



			var allocSpace = Marshal.AllocHGlobal(fullReplyBufferSize); // unmanaged allocation of reply size. TODO Maybe should be allocated on stack
			try
			{
				DateTime start = DateTime.Now;
				var nativeCode = Interop.IcmpSendEcho2Ex(
					Interop.IcmpHandle, //_In_      HANDLE IcmpHandle,
					default(IntPtr), //_In_opt_  HANDLE Event,
					default(IntPtr), //_In_opt_  PIO_APC_ROUTINE ApcRoutine,
					default(IntPtr), //_In_opt_  PVOID ApcContext
					source, //_In_      IPAddr SourceAddress,
					destination, //_In_      IPAddr DestinationAddress,
					sendbuffer, //_In_      LPVOID RequestData,
					(short) sendbuffer.Length, //_In_      WORD RequestSize,
					ref options, //_In_opt_  PIP_OPTION_INFORMATION RequestOptions,
					allocSpace, //_Out_     LPVOID ReplyBuffer,
					fullReplyBufferSize, //_In_      DWORD ReplySize,
					timeout //_In_      DWORD Timeout
					);
				TimeSpan duration = DateTime.Now - start;
				var reply = (Interop.Reply) Marshal.PtrToStructure(allocSpace, typeof (Interop.Reply)); // Parse the beginning of reply memory to reply structure

				byte[] replyBuffer = null;
				if (sendbuffer.Length != 0)
				{
					replyBuffer = new byte[sendbuffer.Length];
					Marshal.Copy(allocSpace + Interop.ReplyMarshalLength, replyBuffer, 0, sendbuffer.Length); //copy the rest of the reply memory to managed byte[]
				}

				if (nativeCode == 0) //Means that native method is faulted.
					return new PingReply(nativeCode, reply.Status, new IPAddress(reply.Address), duration);
				else
					return new PingReply(nativeCode, reply.Status, new IPAddress(reply.Address), reply.RoundTripTime, replyBuffer);
			}
			finally
			{
				Marshal.FreeHGlobal(allocSpace); //free allocated space
			}
		}
Exemplo n.º 10
0
        public static bool SocketBlock = true; // true to block at connection, false to block at login request

        #endregion Fields

        #region Methods

        public static bool IsExempt( IPAddress ip )
        {
            for ( int i = 0; i < Exemptions.Length; i++ )
            {
                if ( ip.Equals( Exemptions[i] ) )
                    return true;
            }

            return false;
        }
Exemplo n.º 11
0
 /// <summary>
 /// Returns the IPv4 subnet mask of the network interface with the given IPv4 address.
 /// </summary>
 public static IPAddress GetSubnetMask(IPAddress address)
 {
     foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces()) {
         foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses) {
             if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork) {
                 if (address.Equals (unicastIPAddressInformation.Address)) {
                     return unicastIPAddressInformation.IPv4Mask;
                 }
             }
         }
     }
     throw new ArgumentException ("Network interface with IPv4 address " + address + " does not exist.");
 }
 //functions
 public static ArrayList calcAddressesSE(IPAddress start, IPAddress end, ProgressBar progress)
 {
     ArrayList addresses = new ArrayList();
     addresses.Add(start);
     if (start.Equals(end))return addresses;
     UInt32 h = 0;
     if (progress != null)
     {
         progress.Value = 0;
         progress.Maximum = (int)(convertIPtoUInt32(end) - convertIPtoUInt32(start));
         Log.WriteLog("Progressbar Maximum (clacAddressesSE): " + progress.Maximum);
     }
     while (!(start.Equals(end)))
     {
         h = convertIPtoUInt32(start);
         h++;
         if (progress != null) progress.PerformStep();
         start = IPAddress.Parse(Convert.ToString(h));
         addresses.Add(start);
     }
     return addresses;
 }
Exemplo n.º 13
0
		/// <summary>
		///     Sends an ARP request to determine a mac address for a given IP address. Uses a stopwatch to count the time for
		///     the request, so duration may be inaccurate. Creates a new thread to use cancellation.
		/// </summary>
		/// <param name="destIp">The address of the requested mac address.</param>
		/// <param name="timeout">
		///     Defines the timeout to wait for the ARP reply to receive. Protocols allows a maximum timeout
		///     around 3000 ms
		/// </param>
		/// <param name="srcIp">the address of the source interface from where the packet should be sent from.</param>
		/// <param name="cancellationHandle">when cancellation handle is set packet is canceled immediately.</param>
		public static ArpReply Send(IPAddress destIp, uint timeout = 0, IPAddress srcIp = null, WaitHandle cancellationHandle = null)
		{
			if (destIp == null)
				throw new ArgumentNullException("destIp");

			var macAddrBuffer = new byte[6];
			var macAddrLength = (uint) macAddrBuffer.Length;
			var srcAddress = srcIp == null ? 0 : (srcIp.Equals(IPAddress.Any) ? 0 : BitConverter.ToInt32(srcIp.GetAddressBytes(), 0));
			var destAddress = BitConverter.ToInt32(destIp.GetAddressBytes(), 0);
			uint nativeCode = 0;




			var task = new Task(() => { nativeCode = Interop.SendARP(destAddress, srcAddress, macAddrBuffer, ref macAddrLength); }, TaskCreationOptions.LongRunning);
			task.Start(TaskScheduler.Default);
			var mre = (task as IAsyncResult).AsyncWaitHandle;



			var wtch = Stopwatch.StartNew();
			if (timeout != 0)
			{
				if (cancellationHandle != null)
				{
					int satisfyedArrayIndex = WaitHandle.WaitAny(new[] {mre, cancellationHandle}, (int) timeout);

					if (satisfyedArrayIndex == WaitHandle.WaitTimeout)
						nativeCode = (uint) ArpStatus.TimedOut;
					else if (satisfyedArrayIndex == 1)
						nativeCode = (uint) ArpStatus.Canceled;
				}
				else if (!mre.WaitOne((int) timeout))
					nativeCode = (uint) ArpStatus.TimedOut;
			}
			else
				mre.WaitOne();

			wtch.Stop();
			var duration = wtch.Elapsed;


			if (nativeCode != 0)
				return new ArpReply(nativeCode, duration);


			var shortenedBytes = new byte[macAddrLength];
			Array.Copy(macAddrBuffer, shortenedBytes, macAddrLength);

			return new ArpReply(nativeCode, duration, shortenedBytes);
		}
Exemplo n.º 14
0
        /// <summary>
        /// 测试IP地址
        /// </summary>
        public static void Test6()
        {
            IPAddress a1 = new IPAddress(new byte[] { 101, 102, 103, 104 });
            IPAddress a2 = IPAddress.Parse("101.102.103.104");
            Console.WriteLine(a1.Equals(a2));
            Console.WriteLine(a1.AddressFamily);
            IPAddress a3 = IPAddress.Parse
  ("[3EA0:FFFF:198A:E4A3:4FF2:54fA:41BC:8D31]");

            IPEndPoint ep = new IPEndPoint(a1, 222);

            Console.WriteLine(a3.AddressFamily);

            Console.WriteLine(ep.ToString());
        }
Exemplo n.º 15
0
        public static bool IsLocalIpAddress(IPAddress hostIp)
        {
            // get local IP addresses
            IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());

            // is localhost
            if (IPAddress.IsLoopback(hostIp)) return true;

            // is local address
            foreach (IPAddress localIp in localIPs)
            {
                if (hostIp.Equals(localIp)) return true;
            }

            return false;
        }
Exemplo n.º 16
0
        public static void HandleOutgoing(byte[] data)
        {
            var packet = new PacketUDP(new MemoryStream(data));

            var ip = new IPAddress(packet.ADDR);
            var port = BitConverter.ToUInt16(packet.PORT, 0);

            // THIS IS WHERE ALL THE MAGIC HAPPENS, BABY
            // Loopback detection: If we're making a request to our external IP, route it!
            // Note that we're rerouting regardless
            if (ip.Equals(ExternalIP) && TargetPorts.Contains(port))
                ip = (IPAddress)UDProxy.gConfiguration.Config["TargetIP"];

            IPEndPoint destination = new IPEndPoint(ip, port);
            TotalUp += MyUDP.Send(packet.DATA, packet.DATA.Length, destination);
        }
Exemplo n.º 17
0
 public static System.Net.IPAddress GetSubnetMask(System.Net.IPAddress address)
 {
     foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
     {
         foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
         {
             if (unicastIPAddressInformation.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
             {
                 if (address.Equals(unicastIPAddressInformation.Address))
                 {
                     return(unicastIPAddressInformation.IPv4Mask);
                 }
             }
         }
     }
     throw new ArgumentException(string.Format("Can't find subnetmask for IP address '{0}'", address));
 }
Exemplo n.º 18
0
        public static bool IsLoopback(IPAddress address)
        {
            if (address == null)
            {
                throw new ArgumentNullException(nameof(address));
            }

            if (address.IsIPv6)
            {
                // Do Equals test for IPv6 addresses
                return(address.Equals(IPv6Loopback));
            }
            else
            {
                return((address.PrivateAddress & LoopbackMask) == (Loopback.PrivateAddress & LoopbackMask));
            }
        }
Exemplo n.º 19
0
 /// <summary>
 /// Check if two ip are equal, using MapToIPv6 if needed
 /// </summary>
 /// <param name="ipAddress">IP address</param>
 /// <param name="other">Other ip address</param>
 /// <returns>True if ip are equal or equal, false otherwise</returns>
 public static bool EqualsWithMapToIPv6(this System.Net.IPAddress ipAddress, System.Net.IPAddress other)
 {
     if (ipAddress.Equals(other))
     {
         return(true);
     }
     try
     {
         IPAddress ipv6      = (ipAddress.IsLocalHost() ? IPAddress.Parse("::1") : ipAddress.MapToIPv6());
         IPAddress otherIPV6 = (other.IsLocalHost() ? IPAddress.Parse("::1") : other.MapToIPv6());
         return(ipv6.Equals(otherIPV6));
     }
     catch
     {
         return(false);
     }
 }
Exemplo n.º 20
0
        /// <summary>
        /// Determines whether the specified address is multicast.
        /// </summary>
        /// <param name="addr">The address.</param>
        /// <returns>
        ///   <c>true</c> if the specified address is multicast; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsMulticast(IPAddress addr)
        {
            // If this is IPv6 then our check is easy
            if (addr.IsIPv6Multicast)
                return true;

            // Otherwise if we're IPv4 look for anything higher than 224.0.0.0
            if (addr.AddressFamily == AddressFamily.InterNetwork)
            {
                // Special case for broadcast since it's above the multicast range
                if (addr.Equals(IPAddress.Broadcast))
                    return false;

                return ((addr.GetAddressBytes()[0] & 240) == 224);
            }

            return false;
        }
        public static IPAddress GetSubnetMask(IPAddress ip)
        {
            foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())
            {
                foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)
                {
                    if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)
                    {
                        if (ip.Equals(unicastIPAddressInformation.Address))
                        {
                            return unicastIPAddressInformation.IPv4Mask;
                        }
                    }
                }
            }

            return null;
        }
Exemplo n.º 22
0
 public static bool IsLoopback(IPAddress address)
 {
     if (address == null)
     {
         throw new ArgumentNullException("address");
     }
     if (address.m_Family == AddressFamily.InterNetworkV6)
     {
         //
         // Do Equals test for IPv6 addresses
         //
         return(address.Equals(IPv6Loopback));
     }
     else
     {
         return((address.m_Address & IPAddress.LoopbackMask) == (IPAddress.Loopback.m_Address & IPAddress.LoopbackMask));
     }
 }
Exemplo n.º 23
0
        /// <summary>
        /// Determines whether the current request is on localhost.
        /// </summary>
        /// <returns>
        ///     <c>true</c> if current request is localhost; otherwise, <c>false</c>.
        /// </returns>
        private static bool IsLocalhost()
        {
            bool localHost = false;

            try
            {
                IPAddress address = IPAddress.Parse(HttpContext.Current.Request.UserHostAddress);
                Debug.WriteLine("IP Address of user: "******"404Handler");

                IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
                Debug.WriteLine("Host Entry of local computer: " + host.HostName, "404Handler");
                localHost = address.Equals(IPAddress.Loopback) || (Array.IndexOf(host.AddressList, address) >= 0);
            }
            catch
            {
                // localhost is false
            }
            return(localHost);
        }
Exemplo n.º 24
0
		public static bool Verify( IPAddress ourAddress, Account account )
		{
			if ( !Enabled )
				return true;

			int count = 0;

			foreach ( var compState in GameServer.Instance.Clients )
			{
				if ( ourAddress.Equals( compState.Address ) && compState.Account != account )
				{
					++count;

					if ( count > MaxAddresses )
						return false;
				}
			}

			return true;
		}
Exemplo n.º 25
0
		// Borrowed from IPInterfaceProperties.cs
		bool HasOnlyDefaultGateway (string iface)
		{
			int gwCount = 0;
			int defaultGwCount = 0;
#if MONODROID
			if (!File.Exists ("/proc/net/route"))
				return false;
			try {
				using (StreamReader reader = new StreamReader ("/proc/net/route")) {
					string line;
					reader.ReadLine (); // Ignore first line
					while ((line = reader.ReadLine ()) != null) {
						line = line.Trim ();
						if (line.Length == 0)
							continue;

						string [] parts = line.Split ('\t');
						if (parts.Length < 3)
							continue;
						string gw_address = parts [2].Trim ();
						byte [] ipbytes = new byte [4];
						if (gw_address.Length == 8 && iface.Equals (parts [0], StringComparison.OrdinalIgnoreCase)) {
							for (int i = 0; i < 4; i++) {
								if (!Byte.TryParse (gw_address.Substring (i * 2, 2), NumberStyles.HexNumber, null, out ipbytes [3 - i]))
									continue;
							}
							IPAddress ip = new IPAddress (ipbytes);
							if (ip.Equals (IPAddress.Any))
								defaultGwCount++;
							else
								gwCount++;
						}
					}
				}
			} catch {
			}
#endif
			return gwCount == 0 && defaultGwCount > 0;
		}
Exemplo n.º 26
0
        public static bool IsLocalHost(IPAddress ip)
        {
            byte[] buff = ip.GetAddressBytes();

            switch (buff[0])
            {
                case 192:
                    if (buff[1] == 168)
                        return true;
                    break;

                case 127:
                    return true;

                case 10:
                    if (buff[1] == 0)
                        return true;
                    break;
            }

            return ip.Equals(Settings.ExternalIP);
        }
Exemplo n.º 27
0
        public static bool SocketBlock = true; // true to block at connection, false to block at login request

        #endregion Fields

        #region Methods

        public static bool Verify( IPAddress ourAddress )
        {
            if ( !Enabled )
                return true;

            ArrayList netStates = NetState.Instances;

            int count = 0;

            for ( int i = 0; i < netStates.Count; ++i )
            {
                NetState compState = (NetState)netStates[i];

                if ( ourAddress.Equals( compState.Address ) )
                {
                    ++count;

                    if ( count > MaxAddresses )
                        return false;
                }
            }

            return true;
        }
Exemplo n.º 28
0
        /// <summary>
        /// IP 比對
        /// </summary>
        /// <param name="source"></param>
        /// <param name="target"></param>
        /// <returns></returns>
        public static bool IPEquals(string source, string target)
        {
            string[] allIp = source.Split(',');
            bool resultStatus = false;
            foreach (string sourceIp in allIp)
            {
                string sIp = sourceIp.Trim();
                string subNetMask = SubnetMask(sIp);
                IPAddress nIpAddress = IPAddress.Parse(sIp.Replace('*', '1'));
                IPAddress nSubnetMask = IPAddress.Parse(subNetMask);
                IPAddress nNetworkAddress = new IPAddress(IPAddress.NetworkToHostOrder(IPAddress.HostToNetworkOrder(nIpAddress.Address) & IPAddress.HostToNetworkOrder(nSubnetMask.Address)));

                IPAddress nIpAddress1 = IPAddress.Parse(target);
                IPAddress nSubnetMask1 = IPAddress.Parse(subNetMask);
                IPAddress nNetworkAddress1 = new IPAddress(IPAddress.NetworkToHostOrder(IPAddress.HostToNetworkOrder(nIpAddress1.Address) & IPAddress.HostToNetworkOrder(nSubnetMask1.Address)));

                resultStatus = nNetworkAddress.Equals(nNetworkAddress1);
                if (resultStatus)
                {
                    break;
                }
            }
            return resultStatus;
        }
Exemplo n.º 29
0
        public static bool Verify( IPAddress ourAddress )
        {
            if ( !Enabled || IsExempt( ourAddress ) )
                return true;

            List<NetState> netStates = NetState.Instances;

            int count = 0;

            for ( int i = 0; i < netStates.Count; ++i )
            {
                NetState compState = netStates[i];

                if ( ourAddress.Equals( compState.Address ) )
                {
                    ++count;

                    if ( count >= MaxAddresses )
                        return false;
                }
            }

            return true;
        }
Exemplo n.º 30
0
		private static ArrayList GetSharedAccounts( IPAddress ipAddress )
		{
			ArrayList list = new ArrayList();

			foreach ( Account acct in Accounts.GetAccounts() )
			{
				IPAddress[] theirAddresses = acct.LoginIPs;
				bool contains = false;

				for ( int i = 0; !contains && i < theirAddresses.Length; ++i )
					contains = ipAddress.Equals( theirAddresses[i] );

				if ( contains )
					list.Add( acct );
			}

			list.Sort( AccountComparer.Instance );
			return list;
		}
Exemplo n.º 31
0
	void CompareIPs (byte [] bytes, string address)
	{
		IPAddress ip = new IPAddress (bytes);
		IPAddress ip2 = IPAddress.Parse (address);
		Assert.IsTrue (ip2.Equals (ip), "#A-" + address);
		Assert.IsTrue (ip.Equals (ip2), "#B-" + address);
	}
Exemplo n.º 32
0
        /// <summary>
        /// This method is one extra layer of checks to make sure someone isn't messing with us
        /// (trying to remove streams they don't own by sending BYE packets for instance)
        /// 
        /// If we know the IPAddress of the request to RemoveStream, make sure it is the same
        /// IPAddress that owns the stream
        /// </summary>
        /// <param name="ssrc"></param>
        /// <param name="ip"></param>
        private void RemoveSSRC(uint ssrc, IPAddress ip)
        {
            lock(streamsAndIPs)
            {
                // TODO - perhaps this should just be an SSRCConflict check (or it has already been done) JVE
                if(streamsAndIPs.Contains(ssrc))
                {
                    if(!ip.Equals(streamsAndIPs[ssrc].senderIP))
                    {
                        eventLog.WriteEntry(string.Format("IPAddress: {0} is trying to remove " +
                            "stream (ssrc: {1}), owned by IPAddress: {2}",
                            ip.ToString(), ssrc, streamsAndIPs[ssrc].senderIP.ToString()),
                            EventLogEntryType.Error, (int)RtpEL.ID.RemoveStreamAttack);

                        return;  // Don't actually remove the stream
                    }
                }
            }

            RemoveSSRC(ssrc);
        }
Exemplo n.º 33
0
 internal static string/*!*/ IPAddressToHostName(IPAddress/*!*/ address, bool doNotReverseLookup) {
     if (address.Equals(IPAddress.Any) || doNotReverseLookup) {
         return address.ToString();
     } else {
         return Dns.GetHostEntry(address).HostName;
     }
 }
Exemplo n.º 34
0
 // TODO: handle other invalid addresses
 internal static IPHostEntry/*!*/ GetHostEntry(IPAddress/*!*/ address, bool doNotReverseLookup) {
     Assert.NotNull(address);
     if (address.Equals(IPAddress.Any) || address.Equals(IPAddress.Loopback)) {
         return MakeEntry(address, doNotReverseLookup);
     } else {
         return Dns.GetHostEntry(address);
     }
 }
Exemplo n.º 35
0
 public static bool IsLoopback(IPAddress address) {
     if (address == null) {
         throw new ArgumentNullException("address");
     }
     if ( address.m_Family == AddressFamily.InterNetworkV6 ) {
         //
         // Do Equals test for IPv6 addresses
         //
         return address.Equals(IPv6Loopback);
     }
     else {
         return ((address.m_Address & IPAddress.LoopbackMask) == (IPAddress.Loopback.m_Address & IPAddress.LoopbackMask));
     }
 }
Exemplo n.º 36
0
        /// <summary>
        /// Prüft, ob für die Kommunikation mit einem bestimmten Client zwingend Verschlüsselung erforderlich ist, oder nicht.
        /// </summary>
        /// <param name="clientAddress">IP-Adresse des Clients</param>
        /// <returns>Wahr, wenn Verschlüsselung erforderlich ist, ansonsten Falsch</returns>
        private bool RequireEncryption(IPAddress clientAddress)
        {
            // Wenn keine Ausnahmen definiert sind ...
            if (clientAddress == null || _securityExemptionList == null || _securityExemptionList.Length == 0)
                // Standardvorgabe zurückgeben
                return _requireCryptoClient;

            // Gefunden-Schalter
            bool found = false;

            // Alle IP-Adrssen der Ausnahmeliste durchgehen
            foreach (IPAddress address in _securityExemptionList)
            {
                // Wenn die aktuelle Adresse gefunden wurde ...
                if (clientAddress.Equals(address))
                {
                    // Gefunden-Schalter setzen
                    found = true;

                    // Schleife abbrechen
                    break;
                }
            }
            // Prüfergebnis bestimmen und zurückgeben
            return found ? !_requireCryptoClient : _requireCryptoClient;
        }
Exemplo n.º 37
0
        static bool ValidateAddress(IPAddress address, ref MessageQueueAndPath found)
        {
            if (found.Uri.HostNameType != UriHostNameType.IPv4 && found.Uri.HostNameType != UriHostNameType.IPv6)
            {
                return true;
            }

            IPAddress foundAddress = IPAddress.Parse(found.Uri.DnsSafeHost);
            bool valid = (address.Equals(foundAddress) ||
                (foundAddress.Equals(IPAddress.Any) && foundAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) ||
                foundAddress.Equals(IPAddress.IPv6Any));
            found = valid ? found : null;
            return valid;
        }
Exemplo n.º 38
0
 /// <summary>
 /// Is empty
 /// </summary>
 /// <param name="address"></param>
 /// <returns></returns>
 public static bool IsEmpty(this IPAddress address)
 {
     return(address == null ||
            address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any) ||
            address.Equals(IPAddress.None) || address.Equals(IPAddress.IPv6None));
 }
Exemplo n.º 39
0
 internal static bool IsAddressLocal(IPAddress ipAddress) {
     IPAddress[] localAddresses = NclUtilities.LocalAddresses;
     for (int i = 0; i < localAddresses.Length; i++)
     {
         if (ipAddress.Equals(localAddresses[i], false))
         {
             return true;
         }
     }
     return false;
 }
Exemplo n.º 40
0
 public static bool IsNetworkAddress(IPAddress vIPAddress, IPAddress vSubnetMask)
 {
     return vIPAddress.Equals(GetNetworkAddress(vIPAddress,vSubnetMask)); // if Network address from passed IP is the passed IP its a network address ;)
 }
Exemplo n.º 41
0
        public void device_OnPacketArrival(object sender, CaptureEventArgs e)
        {
            var time = e.Packet.Timeval.Date;
            var len  = e.Packet.Data.Length;

            var packet = PacketDotNet.Packet.ParsePacket(e.Packet.LinkLayerType, e.Packet.Data);

            var tcpPacket = (PacketDotNet.TcpPacket)packet.Extract(typeof(PacketDotNet.TcpPacket));

            FileStream fs;

            if (tcpPacket != null)
            {
                var ipPacket = (PacketDotNet.IpPacket)tcpPacket.ParentPacket;
                System.Net.IPAddress srcIpP = ipPacket.SourceAddress;
                System.Net.IPAddress dstIpP = ipPacket.DestinationAddress;

                if (srcIpP.Equals(IPAddress.Parse(srcIP)))
                {//&&tcpPacket.DestinationPort==9100) {
                    if (isFin)
                    {
                        fileName = "pcl" + tcpPacket.AcknowledgmentNumber;
                        fileNameSet.Add(fileName);
                        isFin = false;
                    }
                    if (tcpPacket.Fin)
                    {
                        isFin = true;
                    }

                    if ((sequenceNum == -1 && tcpPacket.PayloadData.Length == 0) || (sequenceNum != -1 && tcpPacket.PayloadData.Length == 0))
                    {
                        // do nothing
                    }
                    else if (tcpPacket.PayloadData.Length > 0)
                    {
                        if (File.Exists(fileName))
                        {
                            fs = new FileStream(fileName, FileMode.Append);
                        }
                        else
                        {
                            fs = new FileStream(fileName, FileMode.Create);
                        }
                        BinaryWriter bw = new BinaryWriter(fs);

                        if (sequenceNum == -1 && tcpPacket.PayloadData.Length > 0)
                        {
                            sequenceNum  = tcpPacket.SequenceNumber;
                            sequenceNum += tcpPacket.PayloadData.Length;
                            bw.Write(tcpPacket.PayloadData);
                            label8.Text = "Status: Has Captured Files, Continuing ..";
                        }
                        else if (sequenceNum != -1 && tcpPacket.PayloadData.Length > 0)
                        {
                            if (sequenceNum == tcpPacket.SequenceNumber)
                            {
                                sequenceNum += tcpPacket.PayloadData.Length;
                                bw.Write(tcpPacket.PayloadData);
                            }
                        }
                        bw.Flush();

                        bw.Close();
                        fs.Close();
                    }
                }

                //  if (srcIp.Equals(IPAddress.Parse("192.168.37.130")) && dstIp.Equals(IPAddress.Parse("192.168.37.1"))) {
                //      device.SendPacket(ipPacket);
                //      Console.WriteLine("has send");
                //  }


                int srcPort = tcpPacket.SourcePort;
                int dstPort = tcpPacket.DestinationPort;

                // Console.WriteLine("{0}:{1}:{2},{3} Len={4} {5}:{6} -> {7}:{8}", time.Hour, time.Minute, time.Second, time.Millisecond, len, srcIpP, srcPort, dstIpP, dstPort);
            }
        }