如何比较两个ip地址n C# [英] How to compare two ip address n C#

查看:147
本文介绍了如何比较两个ip地址n C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部好,



我有两个ips一个 10.128.25.36 另一个是 10.128.xx.xx ,现在我想比较这两个,从第二个ip替换xx值,只比较整数值。



任何人都可以告诉我怎么做.. ??



谢谢.. !!



我的尝试:



 HI全部,

我有两个ips一个 10.128.25.36 另一个是 10.128.xx.xx ,现在我想比较这两个,从第二个ip替换xx值,只比较整数值。

任何人都可以告诉我该怎么做.. ??

谢谢.. !!

解决方案

这很复杂,因为IP地址并不像你那么简单可能已经想到了。

您显示的表单称为IPV4,它由四个8位值组成,这些值由点分隔。但是......首先,这些8位值可以用十进制表示,或者用十六进制表示:0x0A.0x80.0x19.0x24,没有任何不同的值。所以你的代码应该允许这个,或任何混合的基础。

第二个是IPV4不是你可能遇到的唯一格式:还有IPV6,这是非常不同的。

 :: 1是Localhost的IP地址
2001:4860:4860 :: 8888是Google DNS IPV6地址





好​​消息是IPAddress类有一个Parse方法,可以使用任何有效的IP地址格式。

坏消息是10.128.xx .xx不是有效的IP地址,它是一种掩码格式。这意味着它无法自动解析,你必须自己处理它们!

如果你只面对IPV4s,那么使用Split来分隔数值,检查那些是否有掩码,如果没有,转换为整数。

之后,它完全取决于比较应该产生的结果,特别是掩码值

HI All,

I have two ips one 10.128.25.36 and another one is 10.128.xx.xx ,now I want to compare these two, replace the xx values from second ip,compare only integer values.

can any one tell me how to do this..??

thanks..!!

What I have tried:

HI All,

I have two ips one 10.128.25.36 and another one is 10.128.xx.xx ,now I want to compare these two, replace the xx values from second ip,compare only integer values.

can any one tell me how to do this..??

thanks..!!

解决方案

This is complicated, because IP addresses are not as simple as you may have thought.
The form you show is called IPV4, and it consists of four 8 bit values which are separated by dots. But... first off, those 8 bit values can be represented in decimal as you show, or in hexadecimal: 0x0A.0x80.0x19.0x24 without the values being any different. So your code should allow for that, or any mixture of bases.
The second is that IPV4 is not the only format you may meet: there is also IPV6 which is very different.

::1                   is the IP address for Localhost
2001:4860:4860::8888  is the Google DNS IPV6 address



The good news is that the IPAddress class has a Parse method which will work with any valid IP address format.
The bad news is that "10.128.xx.xx" is not a valid IP address, it's a mask format. Which means it can't be automatically parsed, and you will have to handle them yourself!
If you are only facing IPV4s, then use Split to separate numeric values, check those for mask and if not, convert to integer.
After that, it's down to you exactly what the comparison should yield, particularly with mask values


这篇关于如何比较两个ip地址n C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆