【问题标题】:How to compare two different IP? [duplicate]如何比较两个不同的IP? [复制]
【发布时间】:2012-10-17 00:42:39
【问题描述】:

可能重复:
compare two ip with C#

如何比较两个IP?通过比较,我的意思是判断 IP1 是否大于 IP2。那可能吗?如我所见,IPAddress 没有该功能。

【问题讨论】:

  • 我尝试比较字符串表示,但事实证明,它不是唯一的。
  • 好吧,NaNNy 提供了一个平等的解决方案,但据我了解,这不是你需要的吗?
  • 你如何想要定义大于?不同家族的地址之间没有明显的排序关系。为什么需要进行这种比较?即使在一个家庭中,比较两个地址似乎也没有多大意义。
  • 我想通过IP枚举为194.44.44.44,194.44.44.45,...,194.44.44.255,194.44.45.0等等
  • 和更大可以定义如下:IP的第一个三元组大于其他IP中的相同三元组自动意味着IP1更大。

标签: c# ip


【解决方案1】:

编辑:请参阅the answer here 以获得更优雅的内容。不过,请注意有关字节序的警告。

Pranay Rana 的回答从根本上被打破了:比较 '11.2.3.4' 和 '1.12.3.4' 将表明它们是相等的。他们显然不是。

IP 地址本质上是特定形式的 32 位整数。您可以使用这个事实编写一个简单的函数,该函数接受字符串值并为您提供整数,这样比较容易比较:

static void Main(string[] args)
{
    string ip1 = "11.2.3.4";
    string ip2 = "1.12.3.4";
    uint ipInt1 = ipAddressToInt(ip1);
    uint ipInt2 = ipAddressToInt(ip2);
    Console.WriteLine(ipInt1 < ipInt2);
    Console.ReadLine();
}

private static uint ipAddressToInt(string ip)
{
    uint retVal;
    System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse(ip);
    byte[] IPBytes = ipAddress.GetAddressBytes(); 

    retVal = (uint)IPBytes[3] << 24;
    retVal += (uint)IPBytes[2] << 16;
    retVal += (uint)IPBytes[1] << 8;
    retVal += (uint)IPBytes[0]; 
    return retVal;
}

注意 ipAddressToInt 函数中的System.Net.IPAddress.Parse。这会在处理输入字符串之前对其进行验证。

【讨论】:

  • 嗨,我更新了我的答案,它将适用于您给出的条件...
  • 您不能使用long ip1 = ip1.Replace(".", ""); 将字符串转换为长整数。如果有的话,它现在比以前更坏了。
  • 我更新了我的答案,你可以检查一下......检查最新的..
  • 我不同意你在这里的字节意义。如果你使第四个字节最重要,你最终会得到例如在192.168.1.1192.168.1.15 之间对11.0.0.10 进行排序
  • (你上一条评论中的那个链接犯了同样的错误——或者更确切地说,依赖于主机的字节序——并且还犯了使用 signed int 的错误,再次搞乱你可能做的任何排序。)
【解决方案2】:

EDIT(这可能适用于 cmets 中指定的所有条件)

string ip1= "1.2.3.4";
string ip2 ="5.6.7.8";

string[] ip1S = ip1.Split(new char[] {'.'});
string[] ip2S = ip2.Split(new char[] {'.'});

for(int i=0;i<4;i++)
{
  if(Convert.ToInt32(ip1S[i]) > Convert.ToInt32(ip2S[i]))
  {
    Console.WriteLine("ip1 is higher");
    break;
  }
  else if(Convert.ToInt32(ip2S[i]) > Convert.ToInt32(ip1S[i])) 
   {
    Console.WriteLine("ip2 is higher");
    break;
  }  
}

你可以像这样做字符串comapre

string ip1= "1.2.3.4";
string ip2 ="5.6.7.8";

string ip1R = ip1.Replace(".","");
string ip2R = ip2.Replace(".","");


Console.WriteLine(String.Compare(ip1R ,ip2R ));

输出

A negative integer    str1 is less than str2.
0                     str1 equals str2.
A positive integer    This instance is greater than value.
-or-
1

MSDN 上的更多更改字符串比较:http://msdn.microsoft.com/en-us/library/fbh501kz(v=vs.80).aspx

【讨论】:

  • -1 不是我的,这行得通,谢谢。寻找更简单的解决方案。
  • 1) 错字stirng 2) 替换需要两个参数3) 不适用于@987654326 @和1.2.34.5
  • @L.B 谢谢你提到的。实际上我问了这个问题,因为认为有一些内置功能。字符串比较我可以自己实现。
  • @L.B - 错误已更新
  • 这仍然会说192.168.1.123192.168.11.23 是一样的。 为什么要删除.
猜你喜欢
  • 2014-07-13
  • 2014-01-12
  • 2013-05-30
  • 2010-12-24
  • 1970-01-01
  • 2017-10-23
  • 1970-01-01
  • 2017-05-16
  • 2011-02-12
相关资源
最近更新 更多