当前位置: 首页>>代码示例>>C#>>正文


C# IPAddress.Equals方法代码示例

本文整理汇总了C#中System.Net.IPAddress.Equals方法的典型用法代码示例。如果您正苦于以下问题:C# IPAddress.Equals方法的具体用法?C# IPAddress.Equals怎么用?C# IPAddress.Equals使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Net.IPAddress的用法示例。


在下文中一共展示了IPAddress.Equals方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: ValidateListenIPAddress

 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));
     }
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:7,代码来源:PeerValidateHelper.cs

示例2: GetMatchingLocalIP

		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;
		}
开发者ID:KroneckerX,项目名称:WCell,代码行数:29,代码来源:NetworkUtil.cs

示例3: UdpTransport

        // 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;
        }
开发者ID:codebutler,项目名称:meshwork,代码行数:11,代码来源:UdpTransport.cs

示例4: IsOnIntranet

        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;
        }
开发者ID:nadar71,项目名称:Krea,代码行数:17,代码来源:RemoteControllerForm.cs

示例5: SendPing

		/// <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
			}
		}
开发者ID:cssack,项目名称:CsGlobals,代码行数:69,代码来源:IcmpProtocol.cs

示例6: IsExempt

        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;
        }
开发者ID:kamronbatman,项目名称:Defiance-AOS-Pre-2012,代码行数:16,代码来源:IPLimiter.cs

示例7: calcAddressesSE

 //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;
 }
开发者ID:tiago-system13,项目名称:BP_LicenseAudit,代码行数:23,代码来源:ControllerNetwork.cs

示例8: GetSubnetMask

 /// <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.");
 }
开发者ID:calaveraDeluxe,项目名称:krpc,代码行数:16,代码来源:NetworkInformation.cs

示例9: Send

		/// <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);
		}
开发者ID:cssack,项目名称:CsGlobals,代码行数:62,代码来源:ArpProtocol.cs

示例10: Test6

        /// <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());
        }
开发者ID:huanshifeichen,项目名称:Codelib,代码行数:18,代码来源:HttpDemo.cs

示例11: IsLocalIpAddress

        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;
        }
开发者ID:JerryBian,项目名称:PhotonSample,代码行数:16,代码来源:PublicIPAddressReader.cs

示例12: HandleOutgoing

        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);
        }
开发者ID:Gnu32,项目名称:UDProxy,代码行数:16,代码来源:UDPServer.cs

示例13: IsMulticast

        /// <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;
        }
开发者ID:kthompson,项目名称:Upnp,代码行数:25,代码来源:IPAddressHelpers.cs

示例14: GetSubnetMask

        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;
        }
开发者ID:TrakHound,项目名称:TrakHound-Community,代码行数:18,代码来源:Network_Functions.cs

示例15: Verify

		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;
		}
开发者ID:xrunuo,项目名称:xrunuo,代码行数:20,代码来源:IPLimiter.cs


注:本文中的System.Net.IPAddress.Equals方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。